0

如何使用来自两个不同数据框的数据构建 pandas 数据透视表?

表 1: 数据框 1

A    B       C    D
1   apple   100 qwerty
2   apple   101 qwerty1
3   apple   102 qwerty2

表 2:

数据框 2

A     B      C    D
1   orange  200 asdfgh1
2   orange  201 asdfgh2
3   orange  202 asdfgh3

数据透视表目标:

目标数据透视表

                    C         D
A         B
1       apple      100      qwerty
        orange     200      asdfgh1
2       apple      101      qwerty1
        orange     201      asdfgh2
4

1 回答 1

2
import pandas as pd

df = pd.DataFrame({'A': [1,2,3], 'B': ['apple']*3 , 'C': [100, 101, 102], 'D': ['qwerty', 'qwerty1', 'qwerty2']})
df2 = pd.DataFrame({'A': [1,2,3], 'B': ['orange']*3 , 'C': [200, 201, 202], 'D': ['asdfgh', 'asdfgh1', 'asdfgh2']})

pd.concat((df,df2)).groupby(['A', 'B']).first()

            C        D
A B
1 apple   100   qwerty
  orange  200   asdfgh
2 apple   101  qwerty1
  orange  201  asdfgh1
3 apple   102  qwerty2
  orange  202  asdfgh2
于 2021-09-30T04:30:11.183 回答