python - Pandas reshape 数据

标签 python pandas

我有一个如下所示的数据框:

Salesman  Height   product      value
  Knut      6        voltage      5
  Knut      6        frequency    1
  Knut      6        speed        3
  Knut      3        voltage      3
  Knut      3        frequency    5
  Knut      3        speed        3
  Steve     6        frequency    2
  Steve     6        voltage      2

我想 reshape 它,使其看起来像这样:

Salesman  Height    voltage  frequency  speed   
  Knut      6        5            1        3
  Knut      3        3            5        3
  Steve     6        2            2        NA    

对于每个“推销员”和“高度”组合,“产品”列的每个值都应更改为列,并保存列值中的值。如果该值不存在,NA 应该是占位符。

这是我第一次接触 Pandas ,并且几乎坚持了下来。研究了 reshape 和枢轴,但没有得到任何结果。

最佳答案

IIUC,使用pivot_table

df.pivot_table(index=['Salesman','Height'],columns='product',values='value',aggfunc='sum').reset_index()
Out[873]: 
product Salesman  Height  frequency  speed  voltage
0           Knut       3        5.0    3.0      3.0
1           Knut       6        1.0    3.0      5.0
2          Steve       6        2.0    NaN      2.0

没有aggfuncreset_index

df.pivot_table(index=['Salesman','Height'],columns='product',values='value')
Out[875]: 
product          frequency  speed  voltage
Salesman Height                           
Knut     3             5.0    3.0      3.0
         6             1.0    3.0      5.0
Steve    6             2.0    NaN      2.0

关于python - Pandas reshape 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47544504/

相关文章:

python - pandas:将字符串列拆分为多列并动态命名列

python - 拼接 Pandas Dataframe 的优化方法

python - 从列表名称作为列名称的多个列表创建数据框

python - 多处理不保存数据

python - Anjuta IDE - 简单的 Python 问题

python - Pandas 数据框 : slicing column values using second column for slice index

python - Pandas 高效过滤 : Same filter condition on multiple columns

Python ctypes addressof CFuncType

python - 有建议的条目

python - 打印家庭表情符号,使用 U+200D 零宽度连接符,直接打印,对比通过列表