转换Pandas数据帧的形状

时间:2017-07-25 23:51:27

标签: pandas dataframe

我想转换如下的数据帧表。它类似于反向单热编码,但不完全相同。有一种优雅的方式吗?

enter image description here

enter image description here

df=pd.DataFrame({'17-07-05': {3142: 1.0, 3214: np.nan},
'17-07-12': {3142: 1.0, 3214: np.nan},
'17-07-19': {3142: np.nan, 3214: np.nan},
'website_id': {3142: 3142, 3214: 3214}})

1 个答案:

答案 0 :(得分:2)

pd.melt

pd.melt(df, 'website_id', var_name='date').sort_values('website_id')

   website_id      date  value
0        3142  17-07-05    1.0
2        3142  17-07-12    1.0
4        3142  17-07-19    NaN
1        3214  17-07-05    NaN
3        3214  17-07-12    NaN
5        3214  17-07-19    NaN