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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With