python - Pandas 从长到宽 reshape ,通过两个变量

标签 python pandas stata reshape

我有长格式的数据,正在尝试重新调整为宽格式,但似乎没有直接的方法可以使用 melt/stack/unstack:

Salesman  Height   product      price
  Knut      6        bat          5
  Knut      6        ball         1
  Knut      6        wand         3
  Steve     5        pen          2

变成:

Salesman  Height    product_1  price_1  product_2 price_2 product_3 price_3  
  Knut      6        bat          5       ball      1        wand      3
  Steve     5        pen          2        NA       NA        NA       NA

我认为 Stata 可以用 reshape 命令做这样的事情。

最佳答案

这是另一个更加充实的解决方案,取自 Chris Albon's site .

创建“长”数据框

raw_data = {'patient': [1, 1, 1, 2, 2],
                'obs': [1, 2, 3, 1, 2],
          'treatment': [0, 1, 0, 1, 0],
              'score': [6252, 24243, 2345, 2342, 23525]}

df = pd.DataFrame(raw_data, columns = ['patient', 'obs', 'treatment', 'score'])

制作“宽”数据

df.pivot(index='patient', columns='obs', values='score')

关于python - Pandas 从长到宽 reshape ,通过两个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22798934/

相关文章:

python - 如果循环更新其自身之外的内容 - 如何构建等效的或 lambda/列表理解?

python - 从 Dataframe Pandas 中的句子中计算最常见的 100 个单词

python - 从 csv 数据框中选择一列

计数模型的随机效应

python - 如何从位置参数增加文件名?

Python - 值错误 : Cannot index with vector containing NA/NaN values

python - 考虑到数据分布,离散化 Pandas 的列

python - 将长表转换为宽表并根据行创建列

python - Python中Stata宏的等价物

linux - Linux 上的 Stata 13 : how to deal with spaces in filepath using export delimited?