Pandas - 转置一列

30

我在使用pandas的转置(transpose)时遇到了困难。

我有如下的数据框(df):

date         name    quantity
1/1/2018     A       5
1/1/2018     B       6
1/1/2018     C       7
1/2/2018     A       9
1/2/2018     B       8
1/2/2018     C       6

最终我想要为每个日期上的所有名称及其数量创建成对相关性。为了实现这一目标,我首先尝试从此数据框中创建以下输出:

 date       A    B    C
 1/1/2018   5    6    7
 1/2/2018   9    8    6

对我来说,转置很困难,因为我可能会得到重复的列标题,但我也不想通过先删除它们来丢失任何数据。我有一种感觉答案可能在一个我不太熟悉的pandas工具中,我可能一直在关注转置...


听起来你最好使用带有多级索引的groupby或者pivot - G. Anderson
https://dev59.com/d-k5XIcBkEYKwwoY9-hg - BENY
3个回答

46

如果您不执行聚合操作,则应优先使用pd.DataFrame.pivot而不是groupby/pivot_table

res = df.pivot(index='date', columns='name', values='quantity')

print(res)

name      A  B  C
date             
1/1/2018  5  6  7
1/2/2018  9  8  6
如果你希望的话,可以使用reset_indexdate提升为一列。

兄弟你太棒了!感谢你提供reset_index的提示。为那些将来遇到这个例子的人展示一个示例将非常有帮助。 - boardkeystown

3

我的解决方案并不比jpp的更好,只是我恰巧遇到了同样的问题,并以不同的方式解决了它。

df.set_index(['date', 'name']).unstack()

结果看起来有点乱,但在我的情况下它有效了:

enter image description here


0
这里是一个 groupby 解决方案,虽然与 pivot 方法相比非常不实用。 我只建议将其作为一种练习,以熟悉pandas的索引。
# Get values of 'quantity' for each date
x = df.groupby('date')['quantity'].agg(list)
# Insert these values into a new data frame
df2 = pd.DataFrame(index=x.index, data=x.to_list(), columns=df['name'].unique())

这将返回:

            A   B   C
date            
1/1/2018    5   6   7
1/2/2018    8   9   6

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接