2

Suppose I have the following data:

>>> import numpy as np
>>> import pandas as pd

>>> data = np.random.randint(low=0, high=9, size=(10, 6))
>>> cols = ['wage1985', 'wage1986', 'hours1985', 'hours1986', 'race', 'edu']
>>> df = pd.DataFrame(data, columns=cols)
>>> df
   wage1985  wage1986  hours1985  hours1986  race  edu
0         8         2          5          0     3    1
1         7         1          5          8     4    1
2         7         5          3          7     3    7
3         8         3          8          3     1    0
4         2         7          1          6     7    2
5         8         1          3          8     1    6
6         4         7          6          6     1    7
7         0         6          6          2     6    8
8         8         7          4          2     0    7
9         2         2          7          2     3    6

Now I want to reshape it from wide to long, but there are some variables (edu, race) with values that should be repeated. The desired output would be something like the following (showing just the first observation).

>>> df_reshaped
   year  wage  hours  race  edu
id                         
0  1985     8      5     3    1
   1986     2      0     3    1
   ...      .      .     .    .
   ...      .      .     .    .
jtorca
  • 1,531
  • 2
  • 17
  • 31
  • Possible duplicate of [Flatten multiple columns in a dataframe to a single column](https://stackoverflow.com/questions/46435329/flatten-multiple-columns-in-a-dataframe-to-a-single-column) – BENY Sep 28 '17 at 21:31

1 Answers1

1
>>> id['id'] = df.index
>>> pd.wide_to_long(df, ["wage", "hours"], i="id", j="year")
         edu  race  wage  hours
id year                        
0  1985    1     3     8      5
1  1985    1     4     7      5
2  1985    7     3     7      3
3  1985    0     1     8      8
4  1985    2     7     2      1
5  1985    6     1     8      3
6  1985    7     1     4      6
7  1985    8     6     0      6
8  1985    7     0     8      4
9  1985    6     3     2      7
0  1986    1     3     2      0
1  1986    1     4     1      8
2  1986    7     3     5      7
3  1986    0     1     3      3
4  1986    2     7     7      6
5  1986    6     1     1      8
6  1986    7     1     7      6
7  1986    8     6     6      2
8  1986    7     0     7      2
9  1986    6     3     2      2
jtorca
  • 1,531
  • 2
  • 17
  • 31