python - 合并两个具有相同模式的 DataFrame

标签 python pandas

假设您有两个 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/

相关文章:

Python Pandas - reshape 数据框

python - Fillna 一次使用多种方法 - pandas

python - Tkinter:更新标签内容和按钮命令

python - Errno 13 权限被拒绝。在 jupyter 笔记本,UBUNTU

Python:如何使用从列计算的乘法字段扩展 DataFrame

python - 如何使用 TimeGrouper 迭代包含不同范围的多个文件

python - 用货币标记列值,字符串单元格除外

python - 尝试用 numpy 向量化迭代计算

python - 导入了必要的包,但我仍然收到 ImportError : cannot import name 'Adam' from 'keras.optimizers'

python - 无法安装 ipykernel。如果 pip 不可用。请使用该包