1
A
回答
2
我认为你需要的DataFrames
名单concat
与DF名称参数keys
,然后取出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
您也可以使用中的自定义名称210:
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
相关问题
- 1. 按行名合并多个数据帧
- 2. 将数据帧转换为json并将其写入文件并将新的数据帧添加到该文件
- 3. 合并数据帧计数
- 4. 加入/合并两列数据帧
- 5. 合并的数据帧
- 6. 合并行的数据帧
- 7. 合并两个数据帧
- 8. 合并熊猫数据帧
- 9. 熊猫:合并数据帧
- 10. 合并两个数据帧
- 11. 熊猫合并数据帧
- 12. 合并数据帧并覆盖值
- 13. 合并两个数据帧的条件
- 14. 将众多.csv数据文件合并为一个数据帧
- 15. 使用SQLite合并和添加数据
- 16. R'合并'正在改变合并数据帧中的数据
- 17. 通过合并SPSS中的文件合并添加个案并添加变量
- 18. 合并数据帧但丢失数据
- 19. 加入,并在数据帧
- 20. 使用rvest后合并数据帧
- 21. 创建文件并添加数据? C++
- 22. 按元素名称组合/合并多个数据帧
- 23. 合并Excel文件的数量并加载到SQL数据库
- 24. 合并数据帧与数组?
- 25. 按名称合并数据帧使用R
- 26. 添加数据帧并根据可用性分割结果
- 27. 组合数据帧并在R中创建包含数据帧名称的列
- 28. 根据行名称将列合并到一个数据帧
- 29. 熊猫据帧合并列
- 30. 如何合并csv文件并使用python添加标题行?
太棒了!请让我再问一个问题。我的文件夹中有很多.txt文件。通过执行“dfs = [df1,df2,df3,df4,df5 .....]来连接这些文件不是一个好主意。有什么办法连接所有文件而不是这个吗? –
是什么让它不是一个好主意? –
例如,我在我的文件夹中有1000个.txt文件,如果我通过执行df1,df2,df3,...来结合这些.txt文件,它将需要永久.... –