答案 0 :(得分:2)
我认为您需要DataFrames
的{{1}}列表,参数keys
用于df名称,然后删除MultiIndex
并创建新列File
:
dfs = [df1,df2, df3]
df = pd.concat(dfs, keys=range(1, len(dfs) + 1))
.reset_index(level=1, drop=True)
.rename_axis('File')
.reset_index()
样品:
df1 = pd.DataFrame({'Product':['a','b','c'],
'Price':[4,5,6]})
print (df1)
Price Product
0 4 a
1 5 b
2 6 c
df2 = pd.DataFrame({'Product':['d','e','g'],
'Price':[9,8,7]})
print (df2)
Price Product
0 9 d
1 8 e
2 7 g
df3 = pd.DataFrame({'Product':['f','z','h'],
'Price':[1,2,4]})
print (df3)
Price Product
0 1 f
1 2 z
2 4 h
dfs = [df1,df2, df3]
df = pd.concat(dfs, keys=range(1, len(dfs) + 1)) \
.reset_index(level=1, drop=True) \
.rename_axis('File').reset_index()
print (df)
File Price Product
0 1 4 a
1 1 5 b
2 1 6 c
3 2 9 d
4 2 8 e
5 2 7 g
6 3 1 f
7 3 2 z
8 3 4 h
您还可以使用list
中的自定义名称:
dfs = [df1,df2,df3]
names = ['file1','file2','file3']
df = pd.concat(dfs, keys=names)
df = df.reset_index(level=1, drop=True).rename_axis('File').reset_index()
print (df)
File Price Product
0 file1 4 a
1 file1 5 b
2 file1 6 c
3 file2 9 d
4 file2 8 e
5 file2 7 g
6 file3 1 f
7 file3 2 z
8 file3 4 h