Pandas中两个数据帧的合并与重排

2024-05-16 20:37:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧,每个看起来像

date       country      value
20100101   country1       1
20100102   country1       2
20100103   country1       3


date       country      value
20100101   country2       4
20100102   country2       5
20100103   country2       6

我想把它们合并成一个数据帧

date       country1     country2
20100101       1           4
20100102       2           5
20100103       3           6

有什么聪明的方法可以在熊猫身上做到这一点吗?你知道吗


Tags: 数据方法datevaluecountrycountry2country1
1条回答
网友
1楼 · 发布于 2024-05-16 20:37:01

这看起来像pivot表,在Pandas中由于一些奇怪的原因被称为unstack。你知道吗

类似于Wes McKinley的“python for data analysis”一书中使用的示例:

bytz = df.groupby(['tz', opersystem])
counts = bytz.size().unstack().fillna(0)

groupby在行中的操作系统,然后将其旋转,使操作系统成为列,就像您的“country*”值一样)。你知道吗

另外,对于cat数据帧,您可以使用pandas.concat。对生成的数据帧执行.reset_index也是很好的,在某些(许多?)中是bc案例索引中的重复值会使pandas失控,在dataframe上使用的.apply上抛出奇怪的异常。你知道吗

相关问题 更多 >