2017-03-04 10 views
0

多くの(数百)CSVをpandasデータフレームに取り込む必要があります。私は、各CSVファイルのパンダデータフレームへの読み込み時に、ファイルが作成された日付を追加する必要があります。ちなみに、これは私がCSVをで読むために使用していますコマンドであるとしてファイルの作成日時を取得 - read_csvのデータフレーム列に追加

time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime('/path/file.csv'))) 

:私はこのコールを使用したCSVファイルの作成日時を取得することができ

path1 = r'/path/' 
all_files_standings = glob.glob(path1 + '/*.csv') 
standings = pd.concat((pd.read_csv(f, low_memory=False, usecols=[7, 8, 9]) for f in standings)) 

私はこれを実行してみましたコール(働いていた):

dt_gm = [time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime('/path/file.csv')))] 

だから、私はそれを拡大してみました:

dt_gm = [time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(f) for f in all_files_standings))] 

と、私はこのエラーを取得:

TypeError: an integer is required (got type generator)

私はこれをどのように解決することができますか?

+0

csvsを列(悪いアイデア)または行(良いアイデア)でデータフレームに読み込みたいですか? –

+0

私は違いを認識していませんでした... – DMan

+0

列を追加すると 'f1_c1、f1_c2、f2_c1、f2_c2、...'のようになります。行を追加すると 'c1、c2'行はファイルごとに値を持ちます。最初のfile1行、次にfile2行、...というようになります。 –

答えて

0

異なるファイルが同じ列を持ち、異なるファイルを行に追加する場合は、

import pandas as pd 
import time 
import os 

# lis of files you want to read 
files = ['one.csv', 'two.csv'] 

column_names = ['c_1', 'c_2', 'c_3'] 

all_dataframes = [] 
for file_name in files: 
    df_temp = pd.read_csv(file_name, delimiter=',', header=None) 
    df_temp.columns = column_names 
    df_temp['creation_time'] = time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file_name))) 
    df_temp['file_name'] = file_name 
    all_dataframes.append(df_temp) 

df = pd.concat(all_dataframes, axis=0, ignore_index=True) 

df 

出力:

enter image description here

あなたは列によって異なるファイルを追加したい場合:

all_dataframes = [] 
for idx, file_name in enumerate(files): 
    df_temp = pd.read_csv(file_name, delimiter=',', header=None) 
    column_prefix = 'f_' + str(idx) + '_' 
    df_temp.columns = [column_prefix + c for c in column_names] 
    df_temp[column_prefix + 'creation_time'] = time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file_name))) 
    all_dataframes.append(df_temp) 

pd.concat(all_dataframes, axis=1) 

出力:

enter image description here

関連する問題