【问题标题】:Writing name of file with data in a single frame Python在单帧 Python 中用数据写入文件名
【发布时间】:2019-04-13 05:37:48
【问题描述】:

我有一个长度为 (141,2) 且重复年份和月份的数据框,我从文件夹中的文件中删除了该数据框,如下所示:

Year          Month
2017            1
2017            1
2017            1
2017            1
2017            1
2017            1
2017            1
.
.

我删除的每个文件都有大约 (20000, 6) 行,我想在每个文件上重复年份和月份。

我列出目录中的文件以删除年份和月份,例如:

path = os.path.join(os.getcwd(),'C:\\.....')
files = [os.path.join(path,i) for i in os.listdir(path) if os.path.isfile(os.path.join(path,i))]

然后从列表files 中,我只是遍历每个文件,例如:

for file in files:
    df['Year'] = os.path.split(file)[1]
    df['Year'] = df['Year'].map(lambda x: str(x)[:-6])

我怎样才能将整个文件写入一个数据框,然后将我重复剥离的这些日期加入到文件的整个长度中?

即:使 (141,2) 数据帧只是追加并成为 (20000,2) 帧?

【问题讨论】:

  • 列表files 正确地列出了您的所有目标文件,没有别的,对吧?你确认了吗?
  • 是的。所有文件都正确连接到列表中。

标签: python python-3.x pandas csv dataframe


【解决方案1】:

Dask 可以轻松地从具有路径通配符的文件中构造数据帧,例如"./*.csv",但这对你的问题来说可能有点过头了。

另一种方法是使用concat

df = pd.concat([pd.read_csv(f, ...) for f in files, ignore_index=True])

编辑:

取消后台处理以执行您的 map 基本上看起来像:

df = []
for file in files:
    tdf = pd.DataFrame()
    tdf['Year'] = os.path.split(file)[1]
    df.append(tdf['Year'].map(lambda x: str(x)[:-6]))
 df = pd.concat(df, ignore_index=True)

【讨论】:

  • 在第二个示例中,您仍应在循环中附加到 list,然后再连接。在循环中附加到 DataFrame 会不必要地在每次迭代时复制数据。
猜你喜欢
  • 1970-01-01
  • 2019-07-27
  • 2018-11-27
  • 1970-01-01
  • 1970-01-01
  • 2016-03-23
  • 2021-12-01
  • 1970-01-01
  • 2014-01-21
相关资源
最近更新 更多