簡體   English   中英

Pandas 合並多個數據框並創建數據透視表

[英]Pandas merge multiple data frames and create pivot_table

如何使用來自兩個不同數據幀的數據構建 pandas pivot 表?

表 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

Pivot表目標:

目標 Pivot 表

                    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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM