数据框列中的一组值
Set of values in dataframe columns
所有!
我有一个数据框。一列包含这样的字符串:'Product1, Product2, foo, bar'.
我用“,”将它们分开,现在我有一列包含产品名称列表。
如何获得一组唯一的产品名称?
首先展平列表列表,然后应用 set
最后转换为 list
:
df = pd.DataFrame(data = {'a':['Product1,Product1,foo,bar','Product1,foo,foo,bar']})
print (df)
a
0 Product1,Product1,foo,bar
1 Product1,foo,foo,bar
a=list(set([item for sublist in df['a'].str.split(',').values.tolist() for item in sublist]))
print (a)
['bar', 'foo', 'Product1']
如果想要每行的唯一值:
df = df['a'].str.split(',').apply(lambda x: list(set(x)))
print (df)
0 [bar, foo, Product1]
1 [bar, foo, Product1]
Name: a, dtype: object
所有!
我有一个数据框。一列包含这样的字符串:'Product1, Product2, foo, bar'.
我用“,”将它们分开,现在我有一列包含产品名称列表。
如何获得一组唯一的产品名称?
首先展平列表列表,然后应用 set
最后转换为 list
:
df = pd.DataFrame(data = {'a':['Product1,Product1,foo,bar','Product1,foo,foo,bar']})
print (df)
a
0 Product1,Product1,foo,bar
1 Product1,foo,foo,bar
a=list(set([item for sublist in df['a'].str.split(',').values.tolist() for item in sublist]))
print (a)
['bar', 'foo', 'Product1']
如果想要每行的唯一值:
df = df['a'].str.split(',').apply(lambda x: list(set(x)))
print (df)
0 [bar, foo, Product1]
1 [bar, foo, Product1]
Name: a, dtype: object