1

I'm working with csv on pandas. I'm trying to break a row like this:

| col1  | col2  | jan | feb | mar |
|-------|-------|-----|-----|-----|
| name1 | place | 23  | 32  | 42  |
| name2 | place | 43  | 666 | 3   |
| name3 | place | 2   | 532 | 420 |

into this:

| col1  | col2  |months | quantity |
|-------|-------|-------|----------|
| name1 | place | jan   | 23       |
| name1 | place | feb   | 32       |
| name1 | place | mar   | 42       |
| name2 | place | jan   | 43       |
| name2 | place | feb   | 666      |
| name2 | place | mar   | 3        |
| name3 | place | jan   | 2        |
| name3 | place | feb   | 532      |
| name3 | place | mar   | 420      |

any function to breakdown rows on pandas?

pandas.melt() does not work as i want, because it does not create the order i intended.

1 Answers1

1

Try:

df.set_index(['col1','col2']).stack().reset_index()

You may need to rename some columns afterwards.

Quang Hoang
  • 146,074
  • 10
  • 56
  • 74