-1

在给定此示例数据框的情况下,如何计算列中每个值在列substring中出现的频率string并将结果附加为新列:

df = pd.DataFrame({
'substring':['a', 'b', 'c', 'a', 'b', 'c', 'd', 'd', 'a']
'string':['a a b', '', 'a a', 'b', 'a b', 'a c a', '', 'b c a', 'd d']})

  substring string
0         a  a a b
1         b      
2         c    a a
3         a      b
4         b    a b
5         c  a c a
6         d       
7         d  b c a
8         a    d d

这里是我希望输出的样子:

  substring string count
0         a  a a b    5
1         b           4
2         c    a a    2
3         a      b    5
4         b    a b    4
5         c  a c a    2
6         d           1
7         d  b c a    1
8         a    d d    5
4

1 回答 1

1

您的问题并不是很明确,但我您想计算字符(或单词?)在整个字符串中出现的次数,而不计算每个字符串的重复次数。

您可以使用转换来设置和collections.Counter

from itertools import chain
from collections import Counter

# count unique elements (here words)
c = Counter(chain.from_iterable(set(x.split()) for x in df['string']))

## alternative for characters
# c = Counter(chain.from_iterable(set(x) for x in df['string']))

# map counts
df['count'] = df['substring'].map(c)

输出:

  substring string  count
0         a  a a b      5
1         b             4
2         c    a a      2
3         a      b      5
4         b    a b      4
5         c  a c a      2
6         d             1
7         d  b c a      1
8         a    d d      5
柜台的纯熊猫变体(相当慢)
c = df['string'].str.split().apply(set).explode().value_counts()
于 2022-02-01T10:57:55.853 回答