如何将多个 CSV 文件添加在一起并添加一个额外的列来指示每个文件的来源?
到目前为止我已经:
import os
import pandas as pd
import glob
os.chdir('C:\...') # path to folder where all CSVs are stored
for f, i in zip(glob.glob('*.csv'), short_list):
df = pd.read_csv(f, header = None)
df.index = i * len(df)
dfs.append(df)
all_data = pd.concat(dfs, ignore_index=True)
除了识别列之外,一切都运行良好。 i
是我想要放入 all_data
的 A 列中的字符串
列表。每列的每一行一个字符串。相反,它返回大量数字,并给出一个 TypeError: Index(....) 必须使用某种集合来调用
。
预期输出:
str1 file1entry1
str1 file1entry2
str1 file1entry3
str2 file2entry1
str2 file2entry2
str2 file2entry3
其中 short_list = ['str1', 'str2', 'str3']
和 file1entry1, file2entry2... etc
来 self 已有的 CSV 文件.
解决方案: 我无法像建议的解决方案那样将所有内容都放在一行中,但是它为我指明了正确的方向。
for f zip(glob.glob('*csv')):
df = pd.read_csv(f, header = None)
df = df.assign(id = os.path.basename(f)) # simpler than pulling from the array. Adds file name to each line.
dfs.append(df)
all_data = pd.concat(dfs)
最佳答案
您可以使用.assign(id=i)方法,它将向每个解析的 CSV 添加 id
列,并用 i
值填充它:
df = pd.concat([pd.read_csv(f, header = None).assign(id=i)
for f, i in zip(glob.glob('*.csv), short_list)],
ignore_index=True)
关于python - 如何将 CSV 文件与 Pandas 结合(并添加识别列),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39603567/