Python:将列分解为列表并消除重复项

时间:2020-02-03 21:32:18

标签: python python-3.x pandas

我有以下数据框:

st = {"name": ['a', 'a||b||c','a||b||c', 'a||c', 'b', 'c']}
df = pd.DataFrame(st)

name
a||b||c
a||b||c
a||c
b
c

我需要获取不同属性值的列表,因此我希望具有a, b, c的列表或集合。我正在考虑使用explode函数,但不能消除重复项。我该怎么做?

1 个答案:

答案 0 :(得分:2)

您的方法链explodedrop_duplicates

df['attr'].str.split('\|\|').explode().drop_duplicates()

0    a
0    b
0    c
Name: attr, dtype: object

或将explodeunique

df['attr'].str.split('\|\|').explode().unique()

array(['a', 'b', 'c'], dtype=object)