[英]Value Count String Occurrences for Pandas Column of Lists type in Python
我有一个 pandas 列,其中包含一个由逗号分隔的字符串列表和一个新行“\n”,如果该列表有多个字符串。 否则,符号很简单: [\n "string" \n] (注意每个新字符串如何有一个 \n 继续它)
是否有可能,对于整个列,计算每个字符串出现的次数?
Outcomes
0 [\n "springs"\n]
1 [\n "to_do"\n]
2 [\n "replace"\n]
3 [\n "null"\n]
4 [\n "finance"\n]
5 [\n "finance"\n]
6 [\n "project_management" ,\n "sprints...
7 [\n "to_do" ,\n "finance...
8 [\n "remote"\n]
9 [\n "get_it_done"\n]
10 [\n "get_it_done" ,\n "remote...
目标 output 应如下所示:
Outcomes Value_count
springs 21
to_do 12
replace 2
null 1
finance 24
project_management 12
get_it_done 22
尝试执行以下操作,但由于 object 类型不可迭代而出现错误
pd.Series([x for item in df['Outcomes'] for x in item]).value_counts()
首先将Series.str.split
与Series.str.split
和Series.str.strip
一起使用:
s = df['Outcomes'].str.split(',').explode().str.strip('[] ').value_counts()
或者通过ast.literal_eval
将值转换为列表:
import ast
pd.Series([x.strip() for item in df['Outcomes'] for x in ast.literal_eval(item)]).value_counts()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.