Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert column with list of values into rows in Pandas DataFrame

Hi I have a dataframe like this:

    A             B  0:  some value    [[L1, L2]] 

I want to change it into:

    A             B  0:  some value    L1 1:  some value    L2 

How can I do that?

like image 780
Agus Sanjaya Avatar asked Oct 10 '16 08:10

Agus Sanjaya


People also ask

How do you convert a column list to a row list in Python?

Method 1: Using T function This is known as the Transpose function, this will convert the list into a row. Here each value is stored in one column.

How do you convert rows into columns and columns into rows in pandas?

Pandas DataFrame: transpose() function The transpose() function is used to transpose index and columns. Reflect the DataFrame over its main diagonal by writing rows as columns and vice-versa. If True, the underlying data is copied. Otherwise (default), no copy is made if possible.

How do I convert a column to a DataFrame in a pandas list?

Use the tolist() Method to Convert a Dataframe Column to a List. A column in the Pandas dataframe is a Pandas Series . So if we need to convert a column to a list, we can use the tolist() method in the Series . tolist() converts the Series of pandas data-frame to a list.


2 Answers

Pandas >= 0.25

df1 = pd.DataFrame({'A':['a','b'],                'B':[[['1', '2']],[['3', '4', '5']]]}) print(df1) 

    A   B 0   a   [[1, 2]] 1   b   [[3, 4, 5]] 

df1 = df1.explode('B') df1.explode('B') 

    A   B 0   a   1 0   a   2 1   b   3 1   b   4 1   b   5 

I don't know how good this approach is but it works when you have a list of items.

like image 93
Pygirl Avatar answered Sep 20 '22 12:09

Pygirl


you can do it this way:

In [84]: df Out[84]:                A               B 0     some value      [[L1, L2]] 1  another value  [[L3, L4, L5]]  In [85]: (df['B'].apply(lambda x: pd.Series(x[0]))    ....:         .stack()    ....:         .reset_index(level=1, drop=True)    ....:         .to_frame('B')    ....:         .join(df[['A']], how='left')    ....: ) Out[85]:     B              A 0  L1     some value 0  L2     some value 1  L3  another value 1  L4  another value 1  L5  another value 

UPDATE: a more generic solution

like image 31
MaxU - stop WAR against UA Avatar answered Sep 18 '22 12:09

MaxU - stop WAR against UA