1

I'm having the pandas DataFrame 'test_df':

email                      my_list
[email protected]          [1,9,3,5]
[email protected]          [6,3,3,15]
[email protected]          [7,7,2,5]
[email protected]          [5,5,5,5]

How can I have this following DataFrame (take the first 2 elem of 'my_list'):

email                      col1             col2             
[email protected]          1                9        
[email protected]          6                3
[email protected]          7                7
[email protected]          5                5           

I tried:

test_df['col1'] = test_df['my_list'][0]
test_df['col2'] = test_df['my_list'][1]

But it's not working

2
  • What is the element type of my_list? IOW, what does type(test_df.my_list[0]) return? Commented Jan 12, 2015 at 5:16
  • thanks for your answer @DSM type(test_df.my_list[0]) <type 'list'> Commented Jan 12, 2015 at 5:22

1 Answer 1

3

I asked a related question here, although I wanted to go a bit beyond expanding the lists into columns so the answers are more complicated than what you need. In your case, you can just do:

# Using my own example data since it's a bit tough to copy-paste
# a printed table and have the lists show up as lists
df = pd.DataFrame({'email': ['[email protected]', '[email protected]'], 
                   'lists': [[1, 9, 3, 5], [6, 3, 3, 15]]})
df
Out[14]: 
           email          lists
0  [email protected]   [1, 9, 3, 5]
1  [email protected]  [6, 3, 3, 15]

objs = [df, pd.DataFrame(df['lists'].tolist()).iloc[:, :2]]
pd.concat(objs, axis=1).drop('lists', axis=1)
Out[13]: 
           email  0  1
0  [email protected]  1  9
1  [email protected]  6  3
Sign up to request clarification or add additional context in comments.

1 Comment

(also sidenote: it's 'column', not 'colon')

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.