1
0

More than 1 year has passed since last update.

複数ファイルの一括読み込みとデータフレームの作成

Last updated at Posted at 2022-11-03

■ライブラリのインポート

import pandas as pd
import glob

■一括で読み込み

file_paths = glob.glob("天気\*.csv")
df = pd.DataFrame()
for file in file_paths:
    tmp = pd.read_csv(file, encoding='cp932')
    df = pd.concat([df,tmp]) 

以上がファイル読込とDFの作成(連結)方法。

おまけ
読込ファイル名などをカラムとして指定したい場合
※今回だと都市名ファイルをスライスして抽出

file_paths = glob.glob(r"天気\*.csv")
df = pd.DataFrame()
for file in file_paths:
    tmp = pd.read_csv(file, encoding='cp932')
    tmp["都市"] = file[-7:-3] #ファイル名の一部をカラム追加したい場合はココで指定
    df = pd.concat([df,tmp]) #縦に結合

都市の文字数によって一部うまくいっていない
image.png

■データクレンジング

#末尾のカンマ消し
df["都市"] = df["都市"].apply(lambda x: x.replace(".","") if str(x).endswith(".") else x)
#津市など一文字都市対応
df["都市"] = df["都市"].apply(lambda x: x.replace("","") if str(x).startswith("") else x)
#\\削除
df["都市"] = df["都市"].apply(lambda x: x.replace("\\","") if str(x).__contains__("\\") else x)

クレンジング後の都市名
image.png

1
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0