![]() |
不开心的消防车 · kettle(MalformedByteSe ...· 5 月前 · |
![]() |
满身肌肉的沙滩裤 · 暗源新品基因原体黎曼鲁斯【战锤40000吧】 ...· 9 月前 · |
![]() |
暗恋学妹的饼干 · 【NTRSLG】迷失的季节 V0.7R3_剧情· 11 月前 · |
![]() |
开朗的硬盘 · 深蓝的故事2:局中人(张译主演《三大队》影视 ...· 1 年前 · |
![]() |
迷茫的火龙果 · 使用Python以优雅的方式实现根据shp数 ...· 1 年前 · |
我有以下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)
但是mostGivenResponse现在是响应的计数,而不是响应本身。
使用
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
编辑:
问题是一个或多个
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
有一个
pd.Series.mode
df.groupby('item').response.transform(pd.Series.mode)
Out[28]:
0 A
1 A
2 A
3 C
4 C
Name: response, dtype: object
您可以使用标准库中的
statistics.mode
:
from statistics import mode
df['mode'] = df.groupby('item')['response'].transform(mode)
print(df)
![]() |
不开心的消防车 · kettle(MalformedByteSequenceException: Invalid byte 2 of 2-byte UTF-8 sequence.)-CSDN博客 5 月前 |
![]() |
暗恋学妹的饼干 · 【NTRSLG】迷失的季节 V0.7R3_剧情 11 月前 |