大熊猫:获取组中出现次数最多的字符串值

马塞尔·霍斯特拉(Marcel Hoekstra)

我有以下DataFrame:

item    response
1       A       
1       A       
1       B       
2       A       
2       A   

我想添加一个列,该列具有最给定的项目响应。这应导致:

item    response  mostGivenResponse
1       A          A
1       A          A      
1       B          A       
2       C          C
2       C          C

我尝试过这样的事情:

df["responseCount"] = df.groupby(["ItemCode", "Response"])["Response"].transform("count")

df["mostGivenResponse"] = df.groupby(['ItemCode'])['responseCount'].transform(max)

但是,大多数GivenResponse现在是响应的计数,而不是响应本身。

耶斯列尔

使用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

collections.Counter.most_common

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

编辑:

问题是只有一个或多个NaNs组,解决方案是使用过滤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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

包含一组中出现次数最多的字符串的最短字符串

给定字符串中出现次数最多的词

Pandas Groupby Agg:获取列表列中出现次数最多的字符串

使用SQL搜索字符串中出现次数最多的值

查找字符串中出现次数最多的字符

查找字符串中出现次数最多的字符

如何获取序列中出现次数最多的元素的值?

如何找到列表中出现次数最多的两个字符串?

python字符串中出现次数最多的最小字母表

搜索出现次数最多的字符串

查找字符串中出现次数最多的字母,然后仅打印字母,而不是计数

查找每个组中出现次数最多的条目

获取数组中出现次数最多的元素

C#:获取列表中出现次数最多的元素?

获取数组JavaScript中出现次数最多的元素

如何获得集合中出现次数最多的值?

如何找到在python词典中出现次数最多的值?

查找子字符串在字符串中连续出现的次数最多

大熊猫数据框,按列比较2组的字符串值

大熊猫加入组中的字符串,跳过 na 值

查找哪个字符出现在字符串中的次数最多

大熊猫从数组中获取嵌套的字符串值

使用powershell在.txt文件中查找出现次数最多的字符串

在 ArrayList 中查找出现次数最多的字符串

无法使用正则表达式找到大熊猫中一组值的子字符串的第一次出现

获取 DataFrame 中某个 id 出现次数最多的值

计算字符串在组列中出现的次数

显示出现次数最多的组

Linq 分组依据并选择子组中出现次数最多的项目