python - 创建转置和 GroupBy 矩阵数据框 Python Pandas
问题描述
我有下表,其中列名 ID、STORE 和 PUSH 可用。
使用每一行的 PUSH 值(在这种情况下,我只有一个 ID,但表包含更多),我想创建第二个表(图中的黄色)。
那么目标是:为每个 STORE(列出 7 adh,ayc,maeg,rot,witz,mar,bud)创建新列,其中每个商店将接收来自 PUSH 列的值。
预期的结果是我将添加到用于生成 ID、STORE、PUSH 表的同一数据框中的黄色表。
任何帮助将不胜感激!
the code I tried was:
df['ADH'] = combined_sf2.groupby('PNO')
['Push'].transform()
df['AYC'] = combined_sf2.groupby('PNO')
['Push'].transform()
df['ADH'] = combined_sf2.groupby('PNO')
['Push'].transform()
df['MAEG'] = combined_sf2.groupby('PNO')
['Push'].transform()
df['ROT'] = combined_sf2.groupby('PNO')
['Push'].transform()
df['WITZ'] = combined_sf2.groupby('PNO')
['Push'].transform()
df['BUD'] = combined_sf2.groupby('PNO')
['Push'].transform()
df['MAR'] = combined_sf2.groupby('PNO')
['Push'].transform()
但是只为所有行重新调整 1 个值
解决方案
# pivot to get the right table format (ID as index, STORE as column
# and PUSH as values).
# the second part (with the loc) is here to repeat the lines according
# to each ID.
pd.pivot(df, index='ID', columns='STORE', values='PUSH').loc[df.ID]
推荐阅读
- c# - 为什么调用 Properties.Settings.Default.Saved() 后我的用户设置没有保留?
- java - Spring 无法调用 Rest Endpoint 得到 404
- google-apps-script - 如何在另一个文档上创建新的时钟触发器
- java - 未选中百里香复选框的Java Spring是空而不是假
- javascript - 带有 set.has 的过滤器无法按预期工作
- java - 收到错误消息 java.lang.IllegalStateException: getWriter() 已被调用!返回 ResponseEntity<> 时
- c - 如何在不使用 C 中的 dirent.h 的情况下列出 Windows 目录中的所有文件?
- bash - 调用函数时 Bash 脚本挂起
- puppeteer - 如何停止木偶录音机录音
- python - 从同一列表中右侧的每个元素中减去列表的每个元素