【问题标题】:groupby pandas dataframe and create another dataframe which represents the groupby results horizontallygroupby pandas 数据框并创建另一个水平表示 groupby 结果的数据框
【发布时间】:2016-07-10 12:06:34
【问题描述】:

我有一个名为 usabledata 的 pandas 数据框,其列 ['marker','action','id']

usabledata = pd.DataFrame(columns=['marker','action','id'])

我在 usabledata 数据帧上运行了以下命令:

counts = usabledata.groupby(['marker','action']).count()
counts = counts.drop(['marker','action'])
print counts

                        id 
marker  action   
1       A               377 
        B               224
        C               9881 
        D               149946 
2       A               481 
        B               397
        C               7468 
        D               147581 
3       A               538 
        B               458
        D               145916

现在,我想创建一个具有以下格式的 pandas 数据框:

Marker      A      B     C     D
1           377    224   9881   149946
2           481    397   7468   147581
3           538    458   0      145916

是否可以在 ipython notebook 中使用 pandas 数据框来做到这一点?

此外,是否可以在获得所需的输出后删除列,例如列“C”?

同一问题的另一个疑问,在获得所需的输出后,如何添加另一列“分数”,它只是“A”和“D”列的比率?

【问题讨论】:

  • @EdChum 你能帮忙吗?

标签: python pandas dataframe


【解决方案1】:

IIUC 然后你可以用fillna 打电话给unstack

In [124]:
gp.unstack().fillna(0)

Out[124]:
       action                   
marker      A    B     C       D
id                              
1         377  224  9881  149946
2         481  397  7468  147581
3         538  458     0  145916

【讨论】:

  • 谢谢@EdChum,您能否检查一下编辑并告诉我是否也可以这样做?
  • 您可以致电drop(columns=['C']) 或将其过滤掉gp.unstack().fillna(0).ix[:,['A','B','D']
  • 我这样做是为了使删除工作。 unstacked = gp.unstack().fillna(0) unstacked.drop(unstacked[['C']])
猜你喜欢
  • 2016-10-13
  • 1970-01-01
  • 1970-01-01
  • 2018-10-27
  • 1970-01-01
  • 2017-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多