Pandas:字符串出现在数据帧单元格中的次数是多少?

问题描述 投票:1回答:2

我相信有一个简单的问题。我有一个pandas数据帧df看起来非常相似:

data = [{"Text" : "Dog", "Dog" : 1},
        {"Text" : "Cat", "Dog" : 0}, 
        {"Text" : "Mouse", "Dog" : 0}, 
        {"Text" : "Dog", "Dog" : 1}]

df = pd.DataFrame(data)

我正在尝试在列Text中搜索多个关键字,并计算它们在每个单元格中出现的次数。结果应该存储在一个新列中,该列显示特定关键字的找到次数。结果应该像Dog列一样。

我尝试使用pandas str.count。它工作得很好。但是在我尝试将结果存储到新列的那一刻,我遇到了麻烦:

mykewords = ('Cat', 'Mouse')
df['Cat'] = df.Text.str.count("Cat")

我收到以下错误消息:

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  if __name__ == '__main__':

我有两个问题:

  1. 我做错了什么,我该如何解决?
  2. 如何遍历mykeywords中的所有关键字并获得每个列?

非常感谢您提前提供任何帮助!

python-3.x string pandas frequency
2个回答
0
投票

如果可能的话,文本中的多个值需要计数值:

mykewords = ('Cat', 'Mouse')
for x in mykewords:
    df[x] = df.Text.str.count(x)

更好的解决方案是使用Series.str.findallSeries.str.len的单词边界:

for x in mykewords:
    df[x] = df.Text.str.findall(r"\b{}\b".format(x)).str.len()

解决方案的差异:

data = [{"Text" : "Dog Cat Catman", "Dog" : 1},
        {"Text" : "Cat Cat", "Dog" : 0}, 
        {"Text" : "Mouse Cat", "Dog" : 0}, 
        {"Text" : "Dog", "Dog" : 1}]

df = pd.DataFrame(data)
df1 = df.copy()
print (df)
   Dog            Text
0    1  Dog Cat Catman
1    0         Cat Cat
2    0       Mouse Cat
3    1             Dog

mykewords = ('Cat', 'Mouse')

for x in mykewords:
    df[x] = df.Text.str.findall(r"\b{}\b".format(x)).str.len()
print (df)
   Dog            Text  Cat  Mouse
0    1  Dog Cat Catman    1      0 <-not match Catman
1    0         Cat Cat    2      0
2    0       Mouse Cat    1      1
3    1             Dog    0      0

for x in mykewords:
    df1[x] = df1.Text.str.count(x)
print (df1)
   Dog            Text  Cat  Mouse
0    1  Dog Cat Catman    2      0 <-match Catman
1    0         Cat Cat    2      0
2    0       Mouse Cat    1      1
3    1             Dog    0      0

2
投票

只需使用最新版本更新pandas并尝试以下代码即可。它对我来说就像一个魅力。

import pandas as pd
data = [{"Text" : "Dog", "Dog" : 1},
        {"Text" : "Cat", "Dog" : 0}, 
        {"Text" : "Mouse", "Dog" : 0}, 
        {"Text" : "Dog", "Dog" : 1}]

df = pd.DataFrame(data)
mykewords = ['Cat', 'Mouse']
for i in mykewords:
    df[i] = df.Text.str.count(i)
© www.soinside.com 2019 - 2024. All rights reserved.