我目前有一个类似于此的数据框
User Date FeatureA FeatureB
John DateA 1 2
John DateB 3 5
无论如何,我可以将两行合并为
User Date1 Date2 FeatureA1 FeatureB1 FeatureA2 FeatureB2
John DateA DateB 1 2 3 5
答案 0 :(得分:2)
I think need:
g = df.groupby(['User']).cumcount()
df = df.set_index(['User', g]).unstack()
df.columns = ['{}{}'.format(i, j+1) for i, j in df.columns]
df = df.reset_index()
print (df)
User Date1 Date2 FeatureA1 FeatureA2 FeatureB1 FeatureB2
0 John DateA DateB 1 3 2 5
Explanation:
User
s with cumcount
set_index
MultiIndex
unstack
MultiIndex
reset_index
index
转换为列
醇>