[英]how to count number of unique string in a column per row in pandas
我有这张桌子
no type
1 123, 234, 345
2 123
3 4567,235
4
我想为每一行计算列type
的字符串数,所以我想添加新的列来显示计数结果。 预期的结果是:
no type count
1 123, 234, 345 3
2 123 1
3 4567,235 2
4 NaN 0
如何使用 Pandas 获得预期结果?
提前致谢
尝试str.count
:
df['count'] = df['type'].str.count(',').add(1).fillna(0)
输出:
no type count
0 1 123, 234, 345 3.0
1 2 123 1.0
2 3 4567,235 2.0
3 4 None 0.0
尝试
df['new'] = df['type'].str.split(',').str.len()
列表理解可能会更快,具体取决于数据大小:
df.assign(count = [len(ent.split(','))
if ent else 0
for ent in df.type.fillna('')]
)
no type count
0 1 123, 234, 345 3
1 2 123 1
2 3 4567,235 2
3 4 None 0
就速度而言,另一种选择可能是在应用 Pandas 的字符串方法之前转换为 ArrowString Dtype。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.