簡體   English   中英

如何使用 pandas.melt 取消透視我的數據框?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM