简体   繁体   中英

Pandas merge multiple data frames and create pivot_table

How can I build a pandas pivot table using data from two different dataframes?

Table 1: Data frame 1

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

Table 2:

Data frame 2

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

Pivot table goal:

Goal Pivot table

                    C         D
A         B
1       apple      100      qwerty
        orange     200      asdfgh1
2       apple      101      qwerty1
        orange     201      asdfgh2
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM