计算每行的链接数并将计数添加为新列

时间:2016-07-23 12:16:01

标签: python pandas

我正在尝试计算' href' ' Body'中的实例列,并将计数值添加为与每行对应的新列。

我可以使用这个来获取链接的数量:

dataframe1['Body'].str.contains('href').sum()

但是,这会找到不是每行的所有行的链接计数,即1770.我尝试了以下操作,它再次分配了所有行的链接计数(即1770)。所以,它也没有用:

dataframe1['LinkCount'] = dataframe1['Body'].str.contains('href').sum()

我想,apply()会起作用,但它会将NaN值作为计数值返回:

dataframe1['LinkCount'] = dataframe1[['Body']].apply(lambda x: x.str.contains('href').sum())

任何人都可以帮助我吗?我做错了什么?

2 个答案:

答案 0 :(得分:1)

> import pandas as pd
> df = pd.DataFrame([["AAAAAAAA"], ["AAABBB"]], columns=['body'])
> df['count'] = df.apply(lambda r: r.body.count('A'), axis=1)
# df['count'] = df.body.count('A') # (better) alternative, as in the answer of MaxU
> df
       body  count
0  AAAAAAAA      8
1    AAABBB      3

这也适用于多行字符串,但不尊重HTML格式,转义,注释等。当然,您必须根据自己的需要调整r.body.count('A')。但我想,r.body.str.contains('href').sum()应该直截了当。

答案 1 :(得分:1)

试试这个:

In [134]: df
Out[134]:
                              Body
0                              aaa
1                      href...href
2                              bbb
3                             href
4  href aaa href bbb href ccc href

In [135]: df['count'] = df.Body.str.findall('href').apply(len)

In [136]: df
Out[136]:
                              Body  count
0                              aaa      0
1                      href...href      2
2                              bbb      0
3                             href      1
4  href aaa href bbb href ccc href      4