我有一个包含2列的数据框,并且我试图创建一个第三列来计算第二列中第一列的出现次数。
sample_df =
Object Text
Banana Banana Banana Banana
Banana Apple Apple Apple
Apple Banana Apple
现在我正在尝试以下代码:
sample_df['Mentions'] = sample_df['Text'].count(sample_df['Object'])
哪个会产生以下错误:
AttributeErrorTraceback (most recent call last)
<ipython-input-65-c9ae4ce28088> in <module>()
----> 1 sample_df['Mentions'] = sample_df['Text'].count(sample_df['Object'])
/usr/local/lib/python2.7/dist-packages/pandas/core/series.pyc in count(self,
level)
1177 level = self.index._get_level_number(level)
1178
-> 1179 lev = self.index.levels[level]
1180 lab = np.array(self.index.labels[level], subok=False, copy=True)
1181
AttributeError: 'RangeIndex' object has no attribute 'levels'
答案 0 :(得分:3)
如果您阅读pd.Series.count
的文档,将会发现它没有按照您的想象做:
Series.count(level=None)
系列中非NA /无效观测值的返回数
您提供了pandas系列作为level参数,该参数无效,这就是为什么您会收到错误消息。供您使用,请尝试以下方法:
df['counter'] = df.apply(lambda x: x.Text.count(x.Object), axis=1)
Object Text counter
0 Banana Banana Banana Banana 3
1 Banana Apple Apple Apple 0
2 Apple Banana Apple 1
如果您关心性能,还可以在此处使用简单的列表理解:
df['counter'] = [i.count(j) for i, j in zip(df.Text, df.Object)]
时间(使用列表理解:D)
df = pd.concat([df]*10000)
%timeit df.apply(lambda x: x.Text.count(x.Object), axis=1)
1.14 s ± 14.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit [i.count(j) for i, j in zip(df.Text, df.Object)]
6.71 ms ± 25 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
答案 1 :(得分:0)
from collections import Counter
def count(row):
temp=row[1].split(' ')
d=Counter(temp)
return d[row[0]]
df['Mentions']=df.apply(lambda x: count(x),axis=1)
print(df)
Object Text Mentions
0 Banana Banana Banana Banana 3
1 Banana Apple Apple Apple 0
2 Apple Banana Apple 1