一个简单的枢轴可能足以满足您的需求,但这是我为再现您期望的输出所做的:
df['idx'] = df.groupby('Salesman').cumcount()
仅在组内计数器/索引内添加即可获得大部分的信息,但列标签将不会如您所愿:
print df.pivot(index='Salesman',columns='idx')[['product','price']] product price idx 0 1 2 0 1 2Salesman Knut bat ball wand 5 1 3Steve 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 HeightSalesman Knutbat ball wand 5 1 3 6Steve 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)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)