我的python代码在下面的示例中正常工作.我的代码组合了一个CSV文件目录并匹配标题.但是,我想更进一步 - 如何添加一个附加所用CSV文件名的列?
import pandas as pd import glob globbed_files = glob.glob("*.csv") #creates a list of all csv files data = [] # pd.concat takes a list of dataframes as an agrument for csv in globbed_files: frame = pd.read_csv(csv) data.append(frame) bigframe = pd.concat(data, ignore_index=True) #dont want pandas to try an align row indexes bigframe.to_csv("Pandas_output2.csv")
Mike Müller.. 18
这应该工作:
import os for csv in globbed_files: frame = pd.read_csv(csv) frame['filename'] = os.path.basename(csv) data.append(frame)
frame['filename']
创建一个名为的新列filename
,os.path.basename()
并将路径/a/d/c.txt
转换为文件名c.txt
.
这应该工作:
import os for csv in globbed_files: frame = pd.read_csv(csv) frame['filename'] = os.path.basename(csv) data.append(frame)
frame['filename']
创建一个名为的新列filename
,os.path.basename()
并将路径/a/d/c.txt
转换为文件名c.txt
.