python - 如何使用 pandas 计算字符串在列中出现的次数

标签 python pandas dataframe

我的DF:

c1 | C2 | C3
A  | B  | C
A  | B  | N
S  | B  | I

我想知道BC2列中出现了多少次。

我希望输出在列表中

期望的输出:

mylist=[3]

最佳答案

如果您稍后想知道字段中出现两个或多个不同值中的多少个,则可以很好地推广一种方法,即使用 value_counts:

df['C2'].value_counts()
Out[28]: 
B     3
Name: C2, dtype: int64

df['C2'].value_counts().tolist()
Out[29]: [3]

df['C2'].value_counts().to_dict()
Out[30]: {'B ': 3}

df['c1'].value_counts()
Out[31]: 
A     2
S     1
Name: c1, dtype: int64

df['c1'].value_counts().tolist()
Out[32]: [2, 1]

df['c1'].value_counts().to_dict()
Out[33]: {'A ': 2, 'S ': 1}

编辑:

要获取根据首次出现排序的 value_counts 列表输出,您可以使用

df['c1'].value_counts().reindex(df['c1'].unique()).tolist()

例如:

df
Out[65]: 
  c1  C2 C3
0  S  B   C
1  A  B   N
2  A  B   I

df['c1'].value_counts().reindex(df['c1'].unique()).tolist()
Out[66]: [1, 2]

关于python - 如何使用 pandas 计算字符串在列中出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44780664/

相关文章:

python - Scintilla 中的交替行着色

python - 如何从 Celery 获取发起任务执行的队列

python - 按小时合并两个日期列

python - 列表仅存储最后一次迭代

python - 使用不按字母顺序排列的 pandas.Dataframe.groupby

python - 使用 beautiful soup 从各种标签中提取标题

python - (Errno::EACCES) pygments.rb 权限被拒绝

python - 将 Pandas 数据框单元格中的字典解析为新行单元格(新列)

python - 是否可以使用 python 复制单元格的 Excel 公式而不是值?

python - 数据框的行或列中的值返回 true 或 false