[英]how to count number of unique string in a column per row in pandas
I have this table我有这张桌子
no type
1 123, 234, 345
2 123
3 4567,235
4
I want to count number of strings in column type
for each row, so I want to add new column in which shows the count result.我想为每一行计算列type
的字符串数,所以我想添加新的列来显示计数结果。 The expected result would be:预期的结果是:
no type count
1 123, 234, 345 3
2 123 1
3 4567,235 2
4 NaN 0
how can I get the expected result by using pandas?如何使用 Pandas 获得预期结果?
thanks in advance提前致谢
Try str.count
:尝试str.count
:
df['count'] = df['type'].str.count(',').add(1).fillna(0)
Output:输出:
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()
A list comprehension might be faster, depending on the data size:列表理解可能会更快,具体取决于数据大小:
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
Another option, in terms of speed, could be to convert to an ArrowString Dtype before applying Pandas' string methods.就速度而言,另一种选择可能是在应用 Pandas 的字符串方法之前转换为 ArrowString Dtype。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.