Home > other >  How to append all rows of all columns of a dataframe below the last row of first column
How to append all rows of all columns of a dataframe below the last row of first column

Time:06-06

I have dataframe like this:

        0                            1                       2                       3
{'id':10:'name':'Paul'}     {'id':10:'age':33}        {'id':10:'name':'Paul'} {'id':10:'name':'Paul'} 
{'id':10:'name':'Paul'}     {'id':10:'age':'Paul'}    {'id':10:'name':'Paul'} {'id':10:'name':'Paul'}
{'id':10:'name':'Paul'}     {'id':10:'name':'Paul'}   {'id':10:'name':'Paul'} {'id':10:'name':'Paul'}
{'id':10:'name':'Paul'}     {'id':10:'name':'Paul'}   {'id':10:'name':'Paul'} None

So, in this example I have 4 columns with 4 rows. Happens that my dataframe has 500 rows and 7 columns, something around 3500 records (there are a few none on column 7)

All rows in all columns are dict type, even though they can be different or not

What I need: How can I transform this dataframe to have only 1 column, by placing all row of column 1 below that last row of column 0 an so on untill all rows of the last column has been placed below the last row of column 0 ?

Expected Result:

         0
{'id':10:'name':'Paul'}             
{'id':10:'name':'Paul'}         
{'id':10:'name':'Paul'}      
{'id':10:'name':'Paul'}     
{'id':10:'age':33} 
{'id':10:'name':'Paul'}
{'id':10:'name':'Paul'}
{'id':10:'name':'Paul'}
{'id':10:'name':'Paul'}
{'id':10:'name':'Paul'}
more rows
None

CodePudding user response:

You can melt, and keep only the value column:

df.melt(value_name=0)[[0]]

output:

                          0
0   {'id':10:'name':'Paul'}
1   {'id':10:'name':'Paul'}
2   {'id':10:'name':'Paul'}
3   {'id':10:'name':'Paul'}
4        {'id':10:'age':33}
5    {'id':10:'age':'Paul'}
6   {'id':10:'name':'Paul'}
7   {'id':10:'name':'Paul'}
8   {'id':10:'name':'Paul'}
9   {'id':10:'name':'Paul'}
10  {'id':10:'name':'Paul'}
11  {'id':10:'name':'Paul'}
12  {'id':10:'name':'Paul'}
13  {'id':10:'name':'Paul'}
14  {'id':10:'name':'Paul'}
15                     None
  • Related