繁体   English   中英

如何查找存储在 pandas 数据框列中的逗号分隔字符串中唯一值的数量?

[英]How to find the number of unique values in comma separated strings stored in an pandas data frame column?

X Unique_in_x
5,5,6,7,8,6,8 4个
5,9,8,0 4个
5,9,8,0 4个
3,2 2个
5,5,6,7,8,6,8 4个

Unique_in_x 是我预期的列。有时 x 列也可能是字符串。

您可以将列表理解与set一起使用

df['Unique_in_x'] = [len(set(x.split(','))) for x in df['x']]

或者使用splitnunique

df['Unique_in_x'] = df['x'].str.split(',', expand=True).nunique(1)

Output:

               x  Unique_in_x
0  5,5,6,7,8,6,8            4
1        5,9,8,0            4
2        5,9,8,0            4
3            3,2            2
4  5,5,6,7,8,6,8            4

您可以使用np.unique()找到列表的唯一值,然后只使用长度

import pandas as pd
import numpy as np

df['Unique_in_x'] = df['X'].apply(lambda x : len(np.unique(x.split(','))))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM