Python 使用pd.concat时添加标识原始数据帧的列
我有一个数据帧字典,如下所示:Python 使用pd.concat时添加标识原始数据帧的列,python,python-3.x,pandas,Python,Python 3.x,Pandas,我有一个数据帧字典,如下所示: test = {'df1':pd.DataFrame({'col1':[3, 5, 1, 4], 'col2':[3, 5, 1, 4]}), 'df2':pd.DataFrame({'col1':[3, 5, 1, 4], 'col2':[3, 5, 1, 4]}), 'df3':pd.DataFrame({'col1':[3, 5, 1, 4], 'col2':[3, 5, 1, 4]}), 'df4':pd.DataFrame({'col1':[3, 5,
test = {'df1':pd.DataFrame({'col1':[3, 5, 1, 4], 'col2':[3, 5, 1, 4]}), 'df2':pd.DataFrame({'col1':[3, 5, 1, 4], 'col2':[3, 5, 1, 4]}), 'df3':pd.DataFrame({'col1':[3, 5, 1, 4], 'col2':[3, 5, 1, 4]}), 'df4':pd.DataFrame({'col1':[3, 5, 1, 4], 'col2':[3, 5, 1, 4]})]
我想连接这些数据帧,但添加一个新列,该列给出值来自哪个数据帧的“标识”(字典键名)。如何做到这一点?如果我做了pd.concat(test.values())
,我会得到我想要的连接,但没有标识列
谢谢,
杰克使用
concat
和键
pd.concat(test.values(),keys=test.keys())
Out[261]:
col1 col2
df1 0 3 3
1 5 5
2 1 1
3 4 4
df2 0 3 3
1 5 5
2 1 1
3 4 4
df3 0 3 3
1 5 5
2 1 1
3 4 4
df4 0 3 3
1 5 5
2 1 1
3 4 4
一种方法是使用
assign
。您可以迭代字典中的所有dfs
,并在执行时指定标识
列:
pd.concat([df.assign(identity=k) for k,df in test.items()])
这给了你:
col1 col2 identity
0 3 3 df1
1 5 5 df1
2 1 1 df1
3 4 4 df1
0 3 3 df2
1 5 5 df2
2 1 1 df2
3 4 4 df2
0 3 3 df3
1 5 5 df3
2 1 1 df3
3 4 4 df3
0 3 3 df4
1 5 5 df4
2 1 1 df4
3 4 4 df4
还有,如何从这个输出中获取
test['df1']
?pd.concat(test.values(),keys=test.keys()).loc['df1']
@astro123@astro123如果这是您需要的,您愿意接受吗?