![](/img/trans.png)
[英]How do I use the pandas.melt function to unpivot a few columns while keeping the rest intact
[英]How can I use pandas.melt to unpivot my dataframe?
我有这样的数据
time close
date
6/1/20 00:00 4375.5
6/1/20 00:15 4374.0
6/1/20 00:30 4376.5
...
我使用 df.pivot(columns='time', values='close') 来输出它(按我的意愿工作)
00:00 00:15 00:30
date
6/1/20 4375.5 4374.0 4376.5
...
我跨时间范围运行 pct 更改 df.pct_change(axis=1)
00:00 00:15 00:30
date
6/1/20 NaN .00312 .00123 #these are just not real calcs, just putting in nums for example
...
现在我想融化 df,但我在这样做时遇到了麻烦。 我希望数据框回到原来的布局
time pct_change
date
6/1/20 00:00 NaN
6/1/20 00:15 .00312
6/1/20 00:30 .00123
...
我想这样做的原因是因为 plotly.express.density_heatmap() 无法读取非熔化形式的数据。 我正在使用 streamlit 并想插入带有 plotly 的图表,但最终图表只需要看起来与 df.style.background_gradient(cmap='green') 相同
from plotly.express as px
#this code doesnt work, but this is how ideally want to input it.
fig = px.density_heatmap(df, x='time', y='date', z='pct_change')
感谢任何提供指导的人!
你错过了一个日期,你可以试试这个方法
df2=df.pivot(index='date', columns=['time'], values='close').pct_change(axis=1)
df2
time 00:00 00:15 00:30
date
6/1/20 NaN -0.000343 0.000572
df2.unstack().reset_index()
time date 0
0 00:00 6/1/20 NaN
1 00:15 6/1/20 -0.000343
2 00:30 6/1/20 0.000572
如果您只有一个适当的日期时间索引,这一切都会变得容易得多:
df.reset_index(inplace=True)
df['datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])
df = df.set_index('datetime').drop(['date', 'time'], axis=1)
print(df.pct_change())
输出:
close
datetime
2020-06-01 00:00:00 NaN
2020-06-01 00:15:00 -0.000343
2020-06-01 00:30:00 0.000572
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.