考虑两个类似的pandas数据透视表,如何在其索引上连接这两个表,例如country
。例如:
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
答案 0 :(得分:2)
如何加入这些表
模糊不清。有很多方法可以加入这些表格。
Form2.panel4
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)