python - Pandas str.count()

标签 python pandas

我有一个包含 2 列的数据框,我正在尝试创建第三列来计算第一列在第二列中出现的次数。

样本_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'

最佳答案

如果您阅读 pd.Series.count 的文档,你会发现它并没有像你想象的那样做:

Series.count(level=None)

Return number of non-NA/null observations in the Series

您提供了 pandas Series 作为 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)

关于python - Pandas str.count(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51619160/

相关文章:

python - 替换python中列表的值

Python编码unicode<>utf-8

python - 计算列表中的连续数字

python-3.x - 为什么 seaborn.pairplot 无法完成绘制此图?

python - 每年用 Pandas 绘制箱线图

python - 如何处理 Pandas Data Frame 中的重复条目?

python - pydantic 设置 : TypeError: cannot pickle '_thread.lock' object

Python 中的 JavaBean 等价物

python - Pandas IndexSlice 因 pd.style 而失败

python - 根据保留 NaN 的列值删除行