[英]Problem in getting the most frequent value row-wise in a Dataframe with Pandas
[英]Replacing a row value with the most frequent value in Pandas Dataframe
我有如下数据框:
| types | freq | TypeList
0 | Q11424 (item) | 29 | Q11424 (item),Q571 (item)
1 | Q571 (item) | 9 | Q11424 (item),Q571 (item)
0 | Q11012 (item) | 6 | Q11012 (item)
0 | Q4830453 (item) | 39 | Q4830453 (item)
0 | Q7725634 (item) | 2 | Q7725634 (item),Q571 (item)
1 | Q571 (item) | 9 | Q7725634 (item),Q571 (item)
0 | Q785479 (item) | 1 | Q785479 (item),Q1344 (item)
1 | Q1344 (item) | 1 | Q785479 (item),Q1344 (item)
列“类型”实际上是“类型列表”的扁平列。 freq列指示列类型中每个值的频率。 这些频率来自整个数据帧。 在这里,我仅添加其中的几行。 例如,Q571在类型列中出现了9次,因此freq = 9。 TypeList列是每个记录的类型的列表。 我想添加一个新的SuperType列,如果TypeList列将包含多个类型,则该列将具有最常见的类型。 例如,我想要以下结果:
| types | freq | TypeList |SuperType
0 | Q11424 (item) | 29 | Q11424 (item),Q571 (item) | Q11424
1 | Q571 (item) | 9 | Q11424 (item),Q571 (item) | Q11424
0 | Q11012 (item) | 6 | Q11012 (item) | Q11012
0 | Q4830453 (item) | 39 | Q4830453 (item) | Q4830453
0 | Q7725634 (item) | 2 | Q7725634 (item),Q571 (item) | Q571
1 | Q571 (item) | 9 | Q7725634 (item),Q571 (item) | Q571
0 | Q785479 (item) | 1 | Q785479 (item),Q1344 (item) | Q785479
1 | Q1344 (item) | 1 | Q785479 (item),Q1344 (item) | Q785479
在第一行中,TypeList列的值为“ Q11424(项目),Q571(项目)”。 因此,我想检查这两种类型的频率,分别是29和9。 并在该行的superType列中分配最常见的类型,在这种情况下为Q11424。
通过使用transform
df['SuperType']=df.sort_values('freq').groupby('TypeList')['types'].transform('last')
df['SuperType']=df.SuperType.str[:-6]
df.sort_index()
Out[1124]:
types freq TypeList SuperType
0 Q11424 (item) 29 Q11424 (item),Q571 (item) Q11424
1 Q571 (item) 9 Q11424 (item),Q571 (item) Q11424
2 Q11012 (item) 6 Q11012 (item) Q11012
3 Q4830453 (item) 39 Q4830453 (item) Q4830453
4 Q7725634 (item) 2 Q7725634 (item),Q571 (item) Q571
5 Q571 (item) 9 Q7725634 (item),Q571 (item) Q571
6 Q785479 (item) 1 Q785479 (item),Q1344 (item) Q1344
7 Q1344 (item) 1 Q785479 (item),Q1344 (item) Q1344
编辑:
df=df.sort_values('freq')
df['SuperType']=df.groupby('TypeList')['types'].transform('last').values
df['SuperType']=df.SuperType.str[:-6]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.