python计算一个字符串在pandas数据帧的整行中出现的次数

时间:2018-01-19 17:09:42

标签: pandas dataframe apply

我有一个基于我之前question的问题。下面的代码运行正常,它告诉我整个行中是否存在search_string。我怎么能修改最后一行,以便它提供匹配数而不是1或0?例如,对于第一行,它应返回4,因为我的search_string出现在该行的4个位置。

sales = [{'account': 'Jones LLC jones', 'Jan': '150', 'Feb': '200', 'Mar': '140 jones jones'},
         {'account': 'Alpha Co',  'Jan': 'Jones', 'Feb': '210', 'Mar': '215'},
         {'account': 'Blue Inc',  'Jan': '50',  'Feb': '90',  'Mar': '95' }]
df = pd.DataFrame(sales)
df

search_string = 'Jones'

(df.apply(lambda x: x.str.contains(search_string))
                       .sum(axis=1).astype(int))

2 个答案:

答案 0 :(得分:2)

您可以使用 <TextBlock x:Name="status_1" HorizontalAlignment="Right" Margin="288,95,0,0" TextWrapping="Wrap" Text="&#xf110;" VerticalAlignment="Top" FontFamily="/InstallerPanes;component/App_Plugins/FontAwesomeIconsDD/assets/font-awesome/fonts/#FontAwesome" Visibility="Visible" RenderTransformOrigin="0.5,0.5"> <TextBlock.RenderTransform> <RotateTransform Angle="0"/> </TextBlock.RenderTransform> </TextBlock> findall

.str.len

输出:

sales = [{'account': 'Jones LLC jones', 'Jan': '150', 'Feb': '200', 'Mar': '140 jones jones'},
         {'account': 'Alpha Co',  'Jan': 'Jones', 'Feb': '210', 'Mar': '215'},
         {'account': 'Blue Inc',  'Jan': '50',  'Feb': '90',  'Mar': '95' }]
df = pd.DataFrame(sales)
df

search_string = 'jones' #Note changed to lowercase j to find more data.

(df.apply(lambda x: x.str.findall(search_string).str.len())
                       .sum(axis=1).astype(int))

将@Vaishali编辑添加到解决方案中:

0    3
1    0
2    0
dtype: int32

输出:

df.apply(lambda x: x.str.lower().str.findall(search_string).str.len()).sum(axis=1).astype(int)

答案 1 :(得分:1)

使用上一个question中的代码,我们只需将any方法更改为sum方法即可。将所有1加起来有效地计算给定行中出现的次数(轴= 1)。

## added and extra Jones into row 1 for 'Jan' column
sales = [{'account': 'Jones LLC', 'Jan': 'Jones', 'Feb': '200', 'Mar': '140'},
         {'account': 'Alpha Co',  'Jan': 'Jones', 'Feb': '210', 'Mar': '215'},
         {'account': 'Blue Inc',  'Jan': '50',  'Feb': '90',  'Mar': '95' }]

df = pd.DataFrame(sales)

df_list = []

for search_string in ['Jones', 'Co', 'Alpha']:
    #use above method but rename the series instead of setting to
    # a columns. The append to a list.
    df_list.append(df.apply(lambda x: x.str.contains(search_string))
                     .sum(axis=1) ## HERE IS SUM in place of any
                     .astype(int)
                     .rename(search_string))

#concatenate the list of series into a DataFrame with the original df
df = pd.concat([df] + df_list, axis=1)
df

Out[2]:
    Feb Jan    Mar   account     Jones  Co   Alpha
0   200 Jones  140   Jones LLC   2      0    0
1   210 Jones  215   Alpha Co    1      1    1
2   90  50     95    Blue Inc    0      0    0