【发布时间】:2014-02-04 15:50:00
【问题描述】:
我想将目标目录中的多个 CSV 文件(具有不同列数)读取到单个 Python Pandas DataFrame 中,以有效地搜索和提取数据。
示例文件:
Events
1,0.32,0.20,0.67
2,0.94,0.19,0.14,0.21,0.94
3,0.32,0.20,0.64,0.32
4,0.87,0.13,0.61,0.54,0.25,0.43
5,0.62,0.21,0.77,0.44,0.16
这是我目前所拥有的:
# get a list of all csv files in target directory
my_dir = "C:\\Data\\"
filelist = []
os.chdir( my_dir )
for files in glob.glob( "*.csv" ) :
filelist.append(files)
# read each csv file into single dataframe and add a filename reference column
# (i.e. file1, file2, file 3) for each file read
df = pd.DataFrame()
columns = range(1,100)
for c, f in enumerate(filelist) :
key = "file%i" % c
frame = pd.read_csv( (my_dir + f), skiprows = 1, index_col=0, names=columns )
frame['key'] = key
df = df.append(frame,ignore_index=True)
(索引无法正常工作)
基本上,下面的脚本正是我想要的(经过试验和测试),但需要循环遍历 10 个或更多 csv 文件:
df1 = pd.DataFrame()
df2 = pd.DataFrame()
columns = range(1,100)
df1 = pd.read_csv("C:\\Data\\Currambene_001y09h00m_events.csv",
skiprows = 1, index_col=0, names=columns)
df2 = pd.read_csv("C:\\Data\\Currambene_001y12h00m_events.csv",
skiprows = 1, index_col=0, names=columns)
keys = [('file1'), ('file2')]
df = pd.concat([df1, df2], keys=keys, names=['fileno'])
我找到了许多相关链接,但是我仍然无法使其正常工作:
【问题讨论】:
-
pandas.concat将允许您使用包含 DataFrame 的任意长度的列表。使用包含所有文件的单个列表提供第一个参数,您将不必再循环脚本。
标签: python csv pandas hierarchical-data