0

Given data in a csv like below

A,B,C-1,D,BTP,Type C1,Type C2
0,1,0,0,0,,Type B
0,2,1,1,14,Type B,Type B
0,3,2,2,28,Type A,Type B
0,4,3,3,42,"Type A,Type B","Type A,Type B"
0,5,4,4,56,Type A,"Type A,Type B"

I'm reading this into a dataframe df. Need to split Type C1' column by ,and store as a list in place such that I can do some lookup with%in% of operator. Here is what is being done.

df["Type C1"] = df["Type C1"].str.split(",", n = 1, expand = True)

Was expecting to get a list for column Type C1 - however it was still a string with the part from , stripped out as below.

      A  B    C-1          D    BTP                        Type C1                Type C2
0     0  1    0            0     0                            NaN                         Type B
1     0  2    1            1    14                         Type B                         Type B
2     0  3    2            2    28                         Type A                         Type B
3     0  4    3            3    42                         Type A                  Type A,Type B
4     0  5    4            4    56                         Type A                  Type A,Type B

For row #3 was expecting [Type A,Type B] for column Type C1

The reference I'm using to do this is from Pandas Split strings into two List/Columns using str.split() Example #1 output.

1
  • 3
    Don't use expand=True. Commented Jun 27, 2020 at 5:03

1 Answer 1

0

You are almost correct, split() returns a list by default:

df['Type C1'] = df['Type C1'].str.split(',')
df['Type C2'] = df['Type C2'].str.split(',')

   A  B  C-1  D  BTP           Type C1           Type C2
0  0  1    0  0    0               NaN          [Type B]
1  0  2    1  1   14          [Type B]          [Type B]
2  0  3    2  2   28          [Type A]          [Type B]
3  0  4    3  3   42  [Type A, Type B]  [Type A, Type B]
4  0  5    4  4   56          [Type A]  [Type A, Type B]
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.