【问题标题】:pandas.dataframe groupby and transposepandas.dataframe 分组和转置
【发布时间】:2019-11-20 12:28:47
【问题描述】:

我是 Python 和 Pandas 的初学者。我很难用文字来解决我的问题,因此,这里是我的数据框的一个示例(还有更多的值和更多的列):

Reason          Grade     
'course'        15
'home'          10
'reputation'    12
'other'         16
'other'         9
'home'          14
'reputation'    10
'reputation'    8
'course'        20
'home'          19
'course'        12
'other'         10
'home'          17
'reputation'    18

而且,我想得到这个:

     course      home     reputation   other
       15         10          12        16
       20         14          10        9
       12         19          8         10
                  17          18

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 你试过df.groupby['Reason']函数了吗?
  • 阅读熊猫groupby。您要实现的目标非常简单。
  • 如果我没记错的话,groupby 必须使用一种方法,比如df.groupby("reason").sum()df.groupby("reason").mean(),但我没有找到一种方法可以返回“count”的所有值"、"家"等
  • @jezrael 您的回答有效,谢谢!

标签: python pandas dataframe pandas-groupby transpose


【解决方案1】:

GroupBy.cumcount 用于Reason 列的计数器,将DataFrame.assign 用于新列,最后使用DataFrame.pivot - 为不存在的值添加缺失值:

df = df.assign(count = df.groupby('Reason').cumcount()).pivot('count','Reason','Grade')
print (df)
Reason  'course'  'home'  'other'  'reputation'
count                                          
0           15.0    10.0     16.0          12.0
1           20.0    14.0      9.0          10.0
2           12.0    19.0     10.0           8.0
3            NaN    17.0      NaN          18.0

【讨论】:

    猜你喜欢
    • 2017-06-17
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 2016-02-15
    • 2016-04-12
    相关资源
    最近更新 更多