简体   繁体   中英

Stack pandas data frame using selected columns

I have a Pandas data frame like this:

  user     1      2       3         4         ...              N
  u1       0.2    0.11    0.1      0.4                         0.5
  u2       0.1    0.3     0.15     0.2        ...              0.2 

. . .

I want to stack this into this form:

  user   site   value
  u1     1      0.2
  u1     2      0.11
  u1     3      0.1

. . .

  u2     1      0.1

The Stack command cannot do this in its normal way. Any idea about this issue?

pandas.melt() does this:

df
Out[3]: 
  user    1     2     3    4
0   u1  0.2  0.11  0.10  0.4
1   u2  0.1  0.30  0.15  0.2

pd.melt(df, id_vars='user', var_name='site', value_name='value')
Out[4]: 
  user site  value
0   u1    1   0.20
1   u2    1   0.10
2   u1    2   0.11
3   u2    2   0.30
4   u1    3   0.10
5   u2    3   0.15
6   u1    4   0.40
7   u2    4   0.20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM