假设您有两个 DataFrame
foo = pd.DataFrame([[123,321],[1543,432]], columns=['id','location'])
bar = pd.DataFrame([[123,421],[1543,436]], columns=['location','id'])
您想要将其合并到一个大表中。但是,由于架构(列)相同,因此应在结果表中添加一个指示“类型”的新列:
id location type
0 123 321 foo
1 1543 432 foo
0 421 123 bar
1 436 1543 bar
目前我所做的是
foo['type'] = ['foo'] * foo.shape[0]
bar['type'] = ['bar'] * bar.shape[0]
pd.concat([foo,bar])
是否有一些更聪明的方法来做到这一点,特别是避免前两行?
最佳答案
您可以将参数keys
添加到concat
- 它创建MultiIndex
:
print (pd.concat([foo,bar], keys=('foo','bar')))
id location
foo 0 123 321
1 1543 432
bar 0 421 123
1 436 1543
对于 MultiIndex
列的使用:
df = pd.concat([foo,bar], keys=('foo','bar'))
.reset_index(drop=True, level=1)
.rename_axis('type')
.reset_index()
print (df)
type id location
0 foo 123 321
1 foo 1543 432
2 bar 421 123
3 bar 436 1543
另一个解决方案 assign
:
df = pd.concat([foo.assign(type='foo'),bar.assign(type='bar')])
print (df)
id location type
0 123 321 foo
1 1543 432 foo
0 421 123 bar
1 436 1543 bar
关于python - 合并两个具有相同模式的 DataFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45914530/