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
首先,请注意,可以使用“sum”连接列表,因为
+
在Python中连接列表:那么:
或:
或:
或:
性能方面,无论您使用
np.unique()
还是collections.Counter
都是一样的,因为df.keywords.sum()
实际上并不那么快。如果您关心性能,pure Python list flattening要快得多:您可以使用纯python解决方案对
chain
进行展平。如果性能很重要,并且按Counter
计算值,请最后使用DataFrame
构造函数:或:
相关问题 更多 >
编程相关推荐