bigDataArtist
bigDataArtist

Reputation: 181

Convert pandas Columns in Rows using (melt doesn't work)

How can I achieve this in pandas, I have a way where I take out each column as a new data frame and then so a insert in SQL but in that way if I have 10 columns I want to do the same I cannot make 10 data frames so I want to know how can I achieve it dynamically

I have a data set where I have the following data

Output I have

Id col1 col2 col3

1  Ab   BC    CD
2  har  Adi   tony

Output I want

Id col1
1  AB
1  BC
1  CD
2  har
2  ADI
2  Tony

Upvotes: 0

Views: 335

Answers (1)

mozway
mozway

Reputation: 260480

melt does work, you just need a few extra steps for the exact output.

Assuming "Id" is a column (if not, reset_index).

(df.melt(id_vars='Id', value_name='col1')
   .sort_values(by='Id')
   .drop('variable', axis=1)
)

Output:

   Id  col1
0   1    Ab
2   1    BC
4   1    CD
1   2   har
3   2   Adi
5   2  tony

Used input:

df = pd.DataFrame({'Id': [1, 2],
                   'col1': ['Ab', 'har'],
                   'col2': ['BC', 'Adi'],
                   'col3': ['CD', 'tony']})

Upvotes: 2

Related Questions