python - 如何计算数据框中所有等于条件的选定单词?

标签 python string python-3.x pandas counter

我有一个数据框,我想在其中计算整个数据框中特定列中的单词数。

假设 shape 是数据框中的一列:

shape                             color
circle rectangle                  orange
square triangle 
rombus  



square oval                       black
triangle circle

rectangle oval                    white
triangle 

我想在 shape 列中计算数据框中有多少个圆形、矩形、椭圆形、三角形。

输出应该是:

circle    2
rectangle 2
triangle  3
oval      1

最佳答案

使用:

L = ['circle','rectangle','oval','triangle']

s = df['shape'].astype(str).str.split(expand=True).stack()
df = s[s.isin(L)].value_counts().reindex(L, fill_value=0).reset_index()
df.columns = ['vals','counts']
print (df)
        vals  counts
0     circle       2
1  rectangle       2
2       oval       2
3   triangle       3

解释:

  1. 第一个split按空格(默认分隔符)和 stack对于 Series 单词
  2. isin 过滤按 list
  3. 中的值
  4. 用于计数 value_counts
  5. 如有必要,更改顺序或使用 0 添加缺失值 添加 reindex
  6. 对于 Series 中的 DataFrame 添加 reset_index

关于python - 如何计算数据框中所有等于条件的选定单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51766834/

相关文章:

python - 如何在 Django channel 消费者中访问 URL 参数

c# - PowerShell - 将 FileTime 转换为 HexString

python - 如何使用python将大量XML插入到另一个XML文件中?

python - 无法重复我的代码中所要求的内容

python - 我正在尝试创建一个程序,将 2 个(用户)输入转换为列表,然后打印列表中的重复项

python - 如何在 Django 的 ORM 中创建等效的 LEFT JOIN 查询 (1.11)

python - 检查 scipy 稀疏矩阵是 CSC 还是 CSR

python - 在 ERPNext 中安装不继续?

c# - 检查字符串是否为 null 或为空,否则将其修剪

python - 从列表中取出字符并将它们变成其他字符