0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

複数csvデータの処理

Posted at

概要

Pythonで複数のcsvデータを重複なしで結合する

Code

sample.py
import os
import glob
import pandas as pd
from tqdm import tqdm #進捗が見える化


#メインの処理
def process(folderPath):
    #カレントディレクトリを指定
    os.chdir(folderPath)

    #結合ファイルパス
    mrgFilePath = 'merge.csv'

    #結合ファイルがあれば削除
    if (os.path.isfile(mrgFilePath)):
        os.remove(mrgFilePath)

    #ファイルパスを取得
    csv_files = glob.glob('*.csv')
    print(csv_files)
    print(len(csv_files))

    # csvデータを読み込んでlistに格納
    encodings = ["shift-jis","UTF-8","EUC-JP"]
    list = []
    for enc in encodings:
        try:
            #フォルダ内のcsvファイルを読み込んでDataFrameに格納
            for file in tqdm(csv_files):
                list.append(pd.read_csv(file,encoding=enc))
                # encodingを指定
                write_encoding = enc
        except: 
            pass

    #結合    
    df_mrg = pd.concat(list)
    # NaNを0にする
    df_mrg.fillna(0, inplace=True)

    #Time[s]列で重複チェックして、重複削除(最初の重複値は残す)
    if 'Time[s]' in df_mrg.columns:
        df_mrg.drop_duplicates(subset=['Time[s]'], inplace=True,keep='first')
    else:
        #0列目で重複チェックして、重複削除(最初の重複値は残す)
        df_mrg.drop_duplicates(subset=[df_mrg.columns[0]], inplace=True,keep='first')

    print('重複行' , df_mrg.duplicated(subset=['Time[s]']).sum())
    #csv書き込み
    df_mrg.to_csv(mrgFilePath,index=False,encoding = write_encoding) 


if __name__== "__main__":
    
    folderPath = r'C:\data'
    process(folderPath)

使い方

1. リスト結合したいcsvファイルをどこでも良いので1つのフォルダに用意する

スクリーンショット 2025-04-25 075256.png

2. フォルダパスを指定する

sample.py
if __name__== "__main__":
    
    folderPath = r'C:\data'
    process(folderPath)

3. 実行
ターミナルにファイル名、数、処理進捗、重複数が表示される
image.png
フォルダ内に結合データができる
image.png

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?