当前位置: 首页 > 面试题库 >

pandas长到宽大的形状,有两个变量

易祖鹤
2023-03-14
问题内容

我有长格式的数据,正尝试将其整形为宽,但似乎没有一种简单的方法可以使用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命令执行类似的操作。


问题答案:

一个简单的枢轴可能足以满足您的需求,但这是我为再现您期望的输出所做的:

df['idx'] = df.groupby('Salesman').cumcount()

仅在组内计数器/索引内添加即可获得大部分的信息,但列标签将不会如您所愿:

print df.pivot(index='Salesman',columns='idx')[['product','price']]

        product              price        
idx            0     1     2      0   1   2
Salesman                                   
Knut         bat  ball  wand      5   1   3
Steve        pen   NaN   NaN      2 NaN NaN

为了更接近您想要的输出,我添加了以下内容:

df['prod_idx'] = 'product_' + df.idx.astype(str)
df['prc_idx'] = 'price_' + df.idx.astype(str)

product = df.pivot(index='Salesman',columns='prod_idx',values='product')
prc = df.pivot(index='Salesman',columns='prc_idx',values='price')

reshape = pd.concat([product,prc],axis=1)
reshape['Height'] = df.set_index('Salesman')['Height'].drop_duplicates()
print reshape

         product_0 product_1 product_2  price_0  price_1  price_2  Height
Salesman                                                                 
Knut           bat      ball      wand        5        1        3       6
Steve          pen       NaN       NaN        2      NaN      NaN       5

编辑:如果您想将程序推广到更多变量,我想您可以做以下事情(尽管可能效率不高):

df['idx'] = df.groupby('Salesman').cumcount()

tmp = []
for var in ['product','price']:
    df['tmp_idx'] = var + '_' + df.idx.astype(str)
    tmp.append(df.pivot(index='Salesman',columns='tmp_idx',values=var))

reshape = pd.concat(tmp,axis=1)

@路加说:

我认为Stata可以使用reshape命令执行类似的操作。

您可以,但我认为您还需要一个组内计数器,以重新配置状态以获得所需的输出:

     +-------------------------------------------+
     | salesman   idx   height   product   price |
     |-------------------------------------------|
  1. |     Knut     0        6       bat       5 |
  2. |     Knut     1        6      ball       1 |
  3. |     Knut     2        6      wand       3 |
  4. |    Steve     0        5       pen       2 |
     +-------------------------------------------+

如果添加,idx则可以在中进行重塑stata

reshape wide product price, i(salesman) j(idx)


 类似资料: