【问题标题】:Get file created date - add to dataframes column on read_csv获取文件创建日期 - 添加到 read_csv 上的数据框列
【发布时间】:2017-07-24 07:39:26
【问题描述】:

我需要将许多(数百个)CSV 提取到 pandas 数据框中。我需要在读入每个 CSV 文件的 pandas 数据框时在列中添加文件的创建日期。我可以使用此调用获取 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:需要一个整数(获取类型生成器)

我该如何解决这个问题?

【问题讨论】:

  • 你想按列(坏主意)还是按行(更好的主意)将 csvs 读入数据帧?
  • 我不知道有什么不同...
  • 如果你添加列,它看起来像f1_c1,f1_c2,f2_c1,f2_c2,...,如果你添加行,它就像c1,c2,并且行将具有文件的值。首先是 file1 行,然后是 file2 行,依此类推。
  • 好的,是的。我按行添加它们
  • 我已经添加了一个答案。看看这是否适合你。

标签: python csv pandas operating-system


【解决方案1】:

如果不同的文件具有相同的列,并且您希望将不同的文件附加到行中。

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

输出:

如果你想按列附加不同的文件:

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)

输出:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 2021-02-01
    • 2013-04-29
    相关资源
    最近更新 更多