【问题标题】:Count how many times a column contains a certain value in Pandas计算一列在 Pandas 中包含某个值的次数
【发布时间】:2018-12-04 06:20:18
【问题描述】:

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

   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()icecream|book 识别为一个值,但是有没有一种方法可以通过计算每个列单元格包含某个值的次数来确定最常见的值,这样“book”将最频繁值?

【问题讨论】:

  • 从技术上讲,正如您所说的那样,它应该返回“o”,因为这是最常见的值,或者“i”,因为这是大多数行包含的值。如果你想让python计算词频,你必须告诉它什么是“词”,即分隔符是什么。

标签: python pandas dataframe counting


【解决方案1】:

splitstack 一起用于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 带有扁平化的列表理解:

from collections import Counter

a = pd.Series(Counter([y for x in df['column_name'] for y in x.split('|')]))
print (a)
book        3
fish        2
icecream    1
campfire    1
dtype: int64

【讨论】:

  • 换个分隔符怎么样?例如:0::icecream||1::campfire||2::fish 而不仅仅是 icecream|campfire ?
  • @Boomer 然后使用this 解决方案并将提取更改为 findall 而不是拆分。
  • @Boomer - 为我工作pd.Series(Counter([y for x in df['column_name'].str.findall('(?<=\:\:)\w+(?=||)') for y in x]))
  • 感谢您帮助我!拥有这么棒的社区,让编程变得更加有趣:)
【解决方案2】:

pd.value_counts

您还可以将列表传递给value_counts 函数。注意我join by | 然后由| 拆分。

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()

df.column_name.str.get_dummies().sum()

book        3
campfire    1
fish        2
icecream    1
dtype: int64

如果您希望对结果进行排序

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

book        3
fish        2
icecream    1
campfire    1
dtype: int64

pd.factorizenp.bincount

注意我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

【讨论】:

    【解决方案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
    

    【讨论】:

    • 我喜欢我的chain + 1 (-:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 2020-08-02
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    • 2021-08-26
    相关资源
    最近更新 更多