1

Given a small dataset as follows:

   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

I need to manipulate room_vector column with the following logic: (1) remove white spaces and replace ; with ,; (2) replace duplicates and keep one seperated by ,.

For the first one, I've tried:

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

Out:

TypeError: unhashable type: 'list'

How could I get the expected result as follows:

   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

Many thanks.

2
  • There are spaces only before/after , and ; ? Commented Nov 9, 2020 at 10:00
  • 1
    Not sure, it could be in any positions. Commented Nov 9, 2020 at 10:01

1 Answer 1

1

Idea is remove whitespaces, then split by , or ; in Series.str.split and then remove duplicates with original order by create dictionary from keys and extracted keys but only for lists else is returned original:

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.