Help us understand the problem. What is going on with this article?

1つのフォルダに置いた複数のcsvファイルをまとめて1つのdataframeにする

More than 1 year has passed since last update.

-globを使ってファイルパスを生成します。
-プログレバーを表示したかったので、tqdmを利用しています。
-日本語が含まれるファイルパスで、それによるエラーを回避するため、engine='python'を追加しています。
-ちょうどindexにしたいものが、Unnamed: 0にあったので、set_index('Unnamed: 0')しています。
-あとあと、重複データがあると困るので、重複確認をしています。any().any()は速度上若干不利らしいですが、わかりやすいので、使っています。

import glob
import sys

import pandas as pd
from tqdm import tqdm


def csvs_to_one_df(path):
    df = pd.DataFrame()

    for file_path in tqdm(glob.glob(path), desc='csv loading'):
        data = pd.read_csv(file_path, dtype=object, engine='python')
        data.columns = data.columns.str.strip()
        data = data.set_index('Unnamed: 0')
        data = data[data.index.notnull()]
        df = pd.concat([df, data])

    df = df.sort_index()

    if df.duplicated().any().any():
        sys.exit('error:重複データあり')

    return df
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした