python—从重复的行中获取值并创建一个新列

vdgimpew  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(212)

我有以下Dataframe:

Year    Name     Town     Vehicle
2000     John     NYC      Truck
2000     John     NYC      Car
2010     Jim     London     Bike
2010     Jim     London     Car

我想把这个Dataframe压缩成每行一行 Year / Name / Town 所以我的最终结果是:

Year    Name     Town     Vehicle    Vehicle2
2000     John     NYC      Truck      Car
2010     Jim     London     Bike      Car

我猜这是某种 df.grouby 语句,但我不知道如何创建新列。任何帮助都将不胜感激!

dxxyhpgq

dxxyhpgq1#

使用 GroupBy.cumcount 对于带有“重塑方式”的计数器 Series.unstack :

g = df.groupby(['Year', 'Name','Town']).cumcount()
df1 = (df.set_index(['Year', 'Name','Town', g])['Vehicle']
         .unstack()
         .add_prefix('Vehicle')
         .reset_index())

print (df1)
   Year  Name    Town Vehicle0 Vehicle1
0  2000  John     NYC    Truck      Car
1  2010   Jim  London     Bike      Car

相关问题