python - 如何在熊猫数据框列中查找文本重合并对其进行计数
问题描述
我有一个像这样的熊猫数据框:
Text like=>apple not=>here
i like apple 0 0
i do not like pears 0 0
one two three 0 0
something here 0 0
something not here 0 0
vla bla bla 0 0
我需要将列填充为:
Text like=>apple not=>here
i like apple 1 0
i do not like pears 0 0
one two three 0 0
something here 0 0
something not here 0 1
vla bla bla 0 0
我不知道除了 Text 列名之外的列名,我需要取列名并计算 Text 列数据中的文本重合度。
我唯一的想法是获取列表中除 Text 列之外的所有列,并通过 iterrows 逐行和逐列名称进行迭代并填充数据,但我认为存在更好的方法来做到这一点。
解决方案
而不是使用iterrows
,您可以实现每列的向量化。
In [41]: df.columns.to_series().drop('Text').values
Out[41]: array(['like=>apple', 'not=>here'], dtype=object)
In [42]: for ele in df.columns.to_series().drop('Text'):
...: column_name = ele.replace('=>', ' ')
...: df[ele] = df.Text.str.count(column_name)
...:
...:
In [43]: df
Out[43]:
Text like=>apple not=>here
0 i like apple 1 0
1 i do not like pears 0 0
2 one two three 0 0
3 something here 0 0
4 something not here 0 1
5 vla bla bla 0 0
推荐阅读
- json - 如何使用 jq 将对象键转换为数组
- gnuplot - gnuplot 在函数评估期间拟合未定义的值
- python - 如何从python中的对象列表生成列表?
- r - UseMethod(“filter_”)中的错误:没有适用于“filter_”的方法应用于类“function”的对象
- python - 使用 psycopg2 连接到 Windows 上的 Postgres 数据库时脚本一直在运行
- scrapy - Scrapy XMLFeedSpider 非常慢
- c++ - 模板显式实例化如何工作?
- algorithm - 如何在 O(log(n)) 中平衡这个 AVL 树?
- firebase - 未在最新的 Firestore 颤振库中获取数据
- php - 显示一个复选框,增加费用,但仅在选择交付选项时可见 Woocommerce