计算一个列在Pandas中包含某个值的次数

2024-09-29 00:13:00 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我的数据帧如下所示:

   column_name
1  book
2  fish
3  icecream|book
4  fish
5  campfire|book

现在,如果我使用df['column_name'].value_counts(),它会告诉我fish是最常用的值。在

但是,我希望返回book,因为第1、3和5行包含单词“book”。在

我知道.value_counts()将{}识别为一个值,但是有没有一种方法可以通过计算每个列单元格包含某个值的次数来确定最频繁的值,这样“book”将是最频繁的值吗?在


Tags: 数据方法namedfvaluecolumn单词次数
3条回答

使用collections.Counter+itertools.chain

from collections import Counter
from itertools import chain

c = Counter(chain.from_iterable(df['column_name'].str.split('|')))

res = pd.Series(c)

print(res)

book        3
campfire    1
fish        2
icecream    1
dtype: int64

^{}^{}一起用于Series

a = df['column_name'].str.split('|', expand=True).stack().value_counts()
print (a)
book        3
fish        2
icecream    1
campfire    1
dtype: int64

或者Counter使用列表理解和扁平化:

^{pr2}$

pd.value_counts

也可以将列表传递给value_counts函数。注I join除以|,然后再除以|。在

pd.value_counts('|'.join(df.column_name).split('|'))

book        3
fish        2
icecream    1
campfire    1
dtype: int64

get_dummies

这是因为数据是用|作为分隔符的。如果有不同的分隔符,请将其传递给get_dummies调用df.column_name.str.get_dummies(sep='|').sum()

^{pr2}$

如果你想把结果排序

df.column_name.str.get_dummies().sum().sort_values(ascending=False)

book        3
fish        2
icecream    1
campfire    1
dtype: int64

pd.factorize和{}

请注意,我join整个列并再次拆分。在

f, u = pd.factorize('|'.join(df.column_name).split('|'))
pd.Series(np.bincount(f), u)

book        3
fish        2
icecream    1
campfire    1
dtype: int64

要排序,我们可以像上面那样使用sort_values。或者这个

f, u = pd.factorize('|'.join(df.column_name).split('|'))
counts = np.bincount(f)
a = counts.argsort()[::-1]
pd.Series(counts[a], u[a])

book        3
fish        2
campfire    1
icecream    1
dtype: int64

相关问题 更多 >