【问题标题】:how to pivot a Dataframe groupby results如何旋转 Dataframe groupby 结果
【发布时间】:2016-12-23 07:58:06
【问题描述】:

我有以下数据框:

test=pd.DataFrame({'MKV':[50,1000,80,20],
                  'Rating':['A','Z','A','A'],
                  'Sec':['I','I','I','F']})

test.groupby(['Rating','Sec'])['MKV'].apply(lambda x: x/x.sum())
gives results:
0   0.38
1   1.00
2   0.62
3   1.00

如何旋转这个 groupby 结果,将每个组的结果放入单独的列中?

【问题讨论】:

  • x/x.sum() 将返回一个系列,而不是一个标量,所以不能这样做。

标签: python pandas group-by pivot


【解决方案1】:

我认为你不需要groupby。您可以使用set_indexunstack 进行透视,然后对列进行规范化:

# Perform the pivot.
test = test.set_index(['Rating','Sec'], append=True).unstack(['Rating','Sec'])

# Normalize the columns.
test = test/test.sum()

# Rename columns as appropriate.
test.columns = [','.join(c[1:]) for c in test.columns]

结果输出:

        A,I  Z,I  A,F
0  0.384615  NaN  NaN
1       NaN  1.0  NaN
2  0.615385  NaN  NaN
3       NaN  NaN  1.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-20
    • 2019-03-19
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2021-03-29
    相关资源
    最近更新 更多