如何从行中删除重复项并将其值转换为 pandas 中的列

How to remove duplicate from rows and convert its value to column in pandas

我有很多以下格式的数据。

Person_ID           Person_value
1                    usr:value1
1                    val:value2
2                    usr:value1
2                    val:value2
3                    usr:value1
3                    val:value2
4                    usr:value1
4                    val:value2

但我想要这样的结果:

Person_ID           Person_value            Person_value2
1                    Usr:value1              val:value2
2                    Usr:value1              val:value2
3                    Usr:value1              val:value2
4                    Usr:value1              val:value2

或像这样::

Person_ID                  Person_value
1                    Usr:value1 // val:value2
2                    Usr:value1 // val:value2
3                    Usr:value1 // val:value2
4                    Usr:value1 // val:value2

由于这些值,它导致这些重复值。保持两者的价值非常重要。

IIUC 使用 GroupBy.cumcount for helper column with pivot:

df1 = (df.assign(a=df.groupby('Person_ID').cumcount().add(1))
         .pivot('Person_ID','a','Person_value')
         .add_prefix('Person_value'))
print (df1)
a           Person_value1 Person_value2
Person_ID                            
A              usr:value1    val:value2
B              usr:value1    val:value2
C              usr:value1    val:value2
D              usr:value1    val:value2

或合计join:

df1 = (df.groupby('Person_ID')
         .agg(' // '.join)
         .reset_index())
print (df1)
  Person_ID              Person_value
0           A  usr:value1 // val:value2
1           B  usr:value1 // val:value2
2           C  usr:value1 // val:value2
3           D  usr:value1 // val:value2

如果有必要按 Person_value: 之前 pivot 之前拆分行:

df1 = (df.assign(a=df['Person_value'].str.split(':').str[0])
         .pivot('Person_ID','a','Person_value'))
print (df1)
a                   usr         val
Person_name                        
A            usr:value1  val:value2
B            usr:value1  val:value2
C            usr:value1  val:value2
D            usr:value1  val:value2