python字符串出现次数最多的_python – Pandas:获取组中出现次数最多的字符串值...

使用

value_counts并返回第一个索引值:

df["responseCount"] = (df.groupby("item")["response"]

.transform(lambda x: x.value_counts().index[0]))

print (df)

item response responseCount

0 1 A A

1 1 A A

2 1 B A

3 2 C C

4 2 C C

from collections import Counter

df["responseCount"] = (df.groupby("item")["response"]

.transform(lambda x: Counter(x).most_common(1)[0][0]))

print (df)

item response responseCount

0 1 A A

1 1 A A

2 1 B A

3 2 C C

4 2 C C

编辑:

问题是只有一个或多个NaN组,解决方案是使用if-else过滤:

print (df)

item response

0 1 A

1 1 A

2 2 NaN

3 2 NaN

4 3 NaN

def f(x):

s = x.value_counts()

print (s)

A 2

Name: 1, dtype: int64

Series([], Name: 2, dtype: int64)

Series([], Name: 3, dtype: int64)

#return np.nan if s.empty else s.index[0]

return np.nan if len(s) == 0 else s.index[0]

df["responseCount"] = df.groupby("item")["response"].transform(f)

print (df)

item response responseCount

0 1 A A

1 1 A A

2 2 NaN NaN

3 2 NaN NaN

4 3 NaN NaN

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值