gpt4 book ai didi

python - 连接两个 pandas 数据透视表

转载 作者:行者123 更新时间:2023-12-01 03:42:39 28 4
gpt4 key购买 nike

考虑两个相似的 pandas 数据透视表,如何将这两个表连接到它们的索引上,例如国家。例如:

df1.pivot_table(index='country', columns='year', values=['rep','sales'], aggfunc='first')

rep sales
year 2013 2014 2015 2016 2013 2014 2015 2016
country
fr None kyle claire None None 10 20 None
uk kyle None None john 12 None None 10
usa None None None john None None None 21


df2.pivot_table(index='country', columns='year', values=['rep','sales'], aggfunc='first')

rep sales
year 2013 2014 2015 2016 2013 2014 2015 2016
country
fr 120 marc debbie None None 0 56 None
uk marc None 100 peter 45 None 65 10
ca 89 None None peter None 33 None 78

最佳答案

How to join these tables

含糊不清。连接这些表的方法有很多种。

设置

idx = pd.Index(['fr', 'uk', 'usa'], name='country')
col = pd.MultiIndex.from_product([['rep', 'sales'], range(2013, 2017)],
names=[None, 'year'])

p1 = pd.DataFrame([
[None, 'kyle', 'claire', None, None, 10, 20, None],
['kyle', None, None, 'john', 12, None, None, 10],
[None, None, None, 'john', None, None, None, 21]
], idx, col, object)

p2 = pd.DataFrame([
[120, 'marc', 'debbie', None, None, 0, 56, None],
['marc', None, 100, 'peter', 45, None, 65, 10],
[89, None, None, 'peter', None, 33, None, 78]
], idx, col, object)
<小时/>

可能的解决方案

p1.combine_first(p2)

enter image description here

<小时/>
pd.concat([p1, p2], axis=1, keys=['p1', 'p2'])

enter image description here

关于python - 连接两个 pandas 数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39314505/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com