问题描述:

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
相关阅读:
Top