替换并删除 Python 中一列中的重复字符串元素

Replace and remove duplicates string elements from one column in Python

给定一个小数据集如下:

   id    room   area            room_vector
0   1   A-102  world        01 , 02, 03, 04
1   2     NaN     24                A; B; C
2   3    B309    NaN         s01, s02 , s02
3   4   C·102     25  E2702-2703,E2702-2703
4   5  E_1089  hello               03,05,06
5   6      27    NaN  05-08,09,10-12, 05-08
6   7      27    NaN                    NaN

我需要使用以下逻辑操作 room_vector 列: (1) 删除white spaces,将;替换为,; (2) 替换重复项并用 ,.

分隔一个

对于第一个,我试过:

df['room_vector'] = df['room_vector'].str.replace([' ', ';'], '')

输出:

TypeError: unhashable type: 'list'

如何得到如下预期结果:

   id    room   area            room_vector
0   1   A-102  world            01,02,03,04
1   2     NaN     24                  A,B,C
2   3    B309    NaN                s01,s02
3   4   C·102     25             E2702-2703
4   5  E_1089  hello               03,05,06
5   6      27    NaN         05-08,09,10-12
6   7      27    NaN                    NaN

非常感谢。

想法是删除空格,然后在 Series.str.split 中按 ,; 拆分,然后通过从键创建字典并提取 keys 来删除具有原始顺序的重复项,但是仅适用于列表,否则返回原件:

f = lambda x: ','.join(dict.fromkeys(x).keys()) if isinstance(x, list) else x
df['room_vector'] = df['room_vector'].str.replace(' ', '').str.split('[,;]').apply(f)
print(df)
   id    room   area     room_vector
0   1   A-102  world     01,02,03,04
1   2     NaN     24           A,B,C
2   3    B309    NaN         s01,s02
3   4   C·102     25      E2702-2703
4   5  E_1089  hello        03,05,06
5   6      27    NaN  05-08,09,10-12
6   7      27    NaN             NaN