gpt4 book ai didi

python - 在所有行中附加多个 CSV 以及每个 CSV 的名称 - Python

转载 作者:行者123 更新时间:2023-11-30 23:19:09 24 4
gpt4 key购买 nike

我在 Python 中有这段代码,它附加位于同一文件中的多个 CSV。运行正常。

import os
import pandas as pd

targetdir = r'E:/Base 2015-1/Carreras'

filelist = os.listdir(targetdir)

big_df=pd.DataFrame()

for filename in filelist:
big_df = big_df.append(pd.read_csv(os.path.join(targetdir, filename), header= None),ignore_index=True)

但是,我想在输出中创建一列,其中包含每行在附加之前的 CSV 名称。例如:

CSV File: A1
1 2 3
a b 3

CSV File: A2
2 4 1
a e r

Append:
1 2 3 A1
a b 3 A1
2 4 1 A2
a e r A2

那么,我如何更改代码才能实现这一点?

最佳答案

我测试了以下内容是否符合您指定的操作:

# from for loop onward... 
for filename in filelist:
tmpdf = pd.read_csv(os.path.join(targetdir, filename),sep=' ',header=None)
tmpdf[len(tmpdf.columns)] = filename # add column with filename
bigdf = pd.concat([bigdf,tmpdf],ignore_index=True)

关于python - 在所有行中附加多个 CSV 以及每个 CSV 的名称 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26224371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com