使用熊猫计算每个索引包含字符串的行数

时间:2019-03-27 18:17:16

标签: python-3.x pandas

我有一个这样的数据集:

index sentence
1     bobby went to the gym
1     sally the bad
1     days are good
2     sunny side up
2     the weird

我想按索引计算“ the”在“句子”列中出现的次数:

index count_the 
1     2
2     1

我该怎么在熊猫里做这件事?

4 个答案:

答案 0 :(得分:1)

首先groupby.Series.apply,然后使用series.str.count

df = df.groupby('index').sentence.apply(' '.join).reset_index()

print(df)
   index                                           sentence
0      1  bobby went to the gym sally the bad days are good
1      2                            sunny side up the weird

df['count_the'] = df.sentence.str.count('the')

print(df.drop(['sentence'],axis=1))
   index  count_the
0      1          2
1      2          1

答案 1 :(得分:0)

df = pd.DataFrame({'index' :[1,1,1,2,2],'sentence':['bobby went to the gym','sally the bad','days are good','sunny side up','the weird']})
df['counts'] = df['sentence'].str.count('the')
print(df.groupby('index')['counts'].sum())

答案 2 :(得分:0)

findall出发的一种方式,请注意我在这里将索引列视为索引

df.sentence.str.findall(r'\bthe\b').str.len().sum(level=0)
Out[363]: 
index
1    2
2    1
Name: sentence, dtype: int64

答案 3 :(得分:0)

您还可以使用groupby()+ apply():

df.groupby('index').apply(lambda x: x['sentence'].str.contains(r'.*the').sum()).reset_index(name = 'count_the')

或groupby()+ apply():

df.groupby('index').agg({'sentence': lambda x: x.str.contains(r'.*the').sum()}).reset_index(name = 'count_the')