python - 如何旋转数据框分组结果

标签 python pandas group-by pivot

我有以下数据框:

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

如何旋转此分组结果,将每个组的结果放入单独的列中? enter image description here

最佳答案

我认为您不需要进行groupby。您可以使用 set_index 进行旋转和 unstack ,然后标准化列:

# 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

关于python - 如何旋转数据框分组结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38983427/

相关文章:

MySQL 两个表最小值和分组依据

python - 在 Python 中使随机模块线程安全

python - 在python中保存列表数据

Python - 从数组中获取最频繁的元素/将 numpy 数组转换为 std 数组

python - 分区(如果适用)

python - 识别并计算数据框中前 x 个对象的统计信息

python - 根据其他数据框python中的值有条件地在数据框中添加一列

python - Pandas 滚动适用于允许nan

sql - 找到每艘船上的水手

sql - 按连接表数据排序的复杂 SQL 查询