使用apply对列表中的元素进行计数

2024-04-26 20:33:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧:

df = pd.DataFrame({
'keywords': [['a', 'b', 'c'], ['c', 'd'], ['a', 'b', 'c', 'd'], ['b', 'c', 'g', 'h', 'i']]})

我想使用df.apply计算列表中所有行的DataFrame中的元素数。我希望上面的数据框给出:

a: 2
b: 3
c: 4
d: 2
g: 1
h: 1
i: 1

Tags: 数据元素dataframedf列表pdapplykeywords
2条回答

首先,请注意,可以使用“sum”连接列表,因为+在Python中连接列表:

df.keywords.sum()
# out: ['a', 'b', 'c', 'c', 'd', 'a', 'b', 'c', 'd', 'b', 'c', 'g', 'h', 'i']

那么:

import collections
collections.Counter(df.keywords.sum())
# out: Counter({'a': 2, 'b': 3, 'c': 4, 'd': 2, 'g': 1, 'h': 1, 'i': 1})

或:

np.unique(df.keywords.sum(), return_counts=True)
# out: (array(['a', 'b', 'c', 'd', 'g', 'h', 'i'], dtype='<U1'),  array([2, 3, 4, 2, 1, 1, 1]))

或:

uniq = np.unique(df.keywords.sum(), return_counts=True)
pd.Series(uniq[1], uniq[0])
# out:
a    2
b    3
c    4
d    2
g    1
h    1
i    1

或:

pd.Series(collections.Counter(df.keywords.sum()))
# out: same as previous

性能方面,无论您使用np.unique()还是collections.Counter都是一样的,因为df.keywords.sum()实际上并不那么快。如果您关心性能,pure Python list flattening要快得多:

collections.Counter([item for sublist in df.keywords for item in sublist])

您可以使用纯python解决方案对chain进行展平。如果性能很重要,并且按Counter计算值,请最后使用DataFrame构造函数:

from itertools import chain
from collections import Counter

c = Counter(chain.from_iterable(df['keywords'].tolist())) 

df = pd.DataFrame({'a': list(c.keys()), 'b':list(c.values())})
print (df)
   a  b
0  a  2
1  b  3
2  c  4
3  d  2
4  g  1
5  h  1
6  i  1

或:

df = pd.DataFrame(df['keywords'].values.tolist()).stack().value_counts().to_frame('a')
print (df)
   a
c  4
b  3
a  2
d  2
g  1
i  1
h  1

相关问题 更多 >