Home > database >  how to extract the list of values from one column in pandas
how to extract the list of values from one column in pandas

Time:09-14

I wish to extract the list of values from one column in pandas how to extract the list of values from one column and then use those values to create additional columns based on number of values within the list.

My dataframe:

a = pd.DataFrame({"test":["","","","",[1,2,3,4,5,6,6],"","",[11,12,13,14,15,16,17]]})

Current output:

test
0   
1   
2   
3   
4   [1, 2, 3, 4, 5, 6, 6]
5   
6   
7   [11, 12, 13, 14, 15, 16, 17]

expected output:

    example_1   example_2   example_3   example_4   example_5   example_6   example_7
0                           
1                           
2                           
3                           
4   1   2   3   4   5   6   6
5                           
6   11  12  13  14  15  16  17

lets say we expect it to have 7 values for each list. <- this is most of my current case so if I can set the limit then it will be a good one. Thank you.

CodePudding user response:

This should be what you're looking for. I replaced the nan values with blank cells, but you can change that of course.

a = pd.DataFrame({"test":["","","","",[1,2,3,4,5,6,6],"","",[11,12,13,14,15,16,17]]})

ab = a.test.apply(pd.Series).fillna("")
ab.columns = ['example_'   str(i) for i in range(1, 8)]

Output:

enter image description here

Edit: using .add_prefix() as the other answer uses is prettier than setting the column names manually with a list comprehension.

CodePudding user response:

Here's a one-liner:

(pd.DataFrame
 (a.test.apply(pd.Series)
 .fillna("")
 .set_axis(range(1, a.test.str.len().max()   1), axis=1)
 .add_prefix("example_")
)

The set_axis is just to make the columns 1-indexed, if you don't mind 0-indexing you can leave it out.

  • Related