首页 > 解决方案 > 如何在熊猫数据框列中查找文本重合并对其进行计数

问题描述

我有一个像这样的熊猫数据框:

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 逐行和逐列名称进行迭代并填充数据,但我认为存在更好的方法来做到这一点。

标签: pythonpandasdataframe

解决方案


而不是使用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

推荐阅读