如何在pandas dataframe列中查找文本重合并计数

时间:2018-07-04 19:44:44

标签: python pandas dataframe

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

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列数据中的文本重合。

我唯一的想法是将列表中除“文本”列之外的所有列都通过逐行,逐列的名称迭代来迭代并填充数据,但是我想存在一种更好的方法。 / p>

1 个答案:

答案 0 :(得分:1)

您无需使用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