簡體   English   中英

Pandas 將日期重新索引到列表中的日期子集

[英]Pandas reindex Dates To Subset of Dates from List

很抱歉,但是有在線文檔和示例,我仍然不明白。 我有一個帶有日期時間格式(yyyy-mm-dd)的日期索引的pandas df,我正在嘗試根據相同格式(yyyy-mm-dd)的日期子集重新采樣或重新索引此數據幀在一個列表中。 我已使用以下方法將 df.index 值轉換為日期時間:

dfmla.index = pd.to_datetime(dfmla.index)

我嘗試了各種方法,並且在應用重新索引后我不斷得到 NaN。 我知道這一定是數據類型問題,我的 df 格式為:

df.dtypes
Out[30]: 
month                int64
mean_mon_flow      float64
std_mon_flow       float64
monthly_flow_ln    float64
std_anomaly        float64
dtype: object

我的數據如下所示:

df.head(5)
Out[31]: 
            month  mean_mon_flow  std_mon_flow  monthly_flow_ln  std_anomaly
date                                                                        
1949-10-01     10       8.565828      0.216126         8.848631     1.308506
1949-11-01     11       8.598055      0.260254         8.368006    -0.883938
1949-12-01     12       8.612080      0.301156         8.384662    -0.755149
1950-08-01      8       8.614236      0.310865         8.173776    -1.416887
1950-09-01      9       8.663943      0.351730         8.437089    -0.644967

我的month_list(列表數據類型)如下所示:

month_list[0:2]
Out[37]: ['1950-08-01', '1950-09-01']

我需要我的精簡、新的重新索引 df 看起來像這樣:

            month  mean_mon_flow  std_mon_flow  monthly_flow_ln  std_anomaly
date                                                                        
1950-08-01      8       8.614236      0.310865         8.173776    -1.416887
1950-09-01      9       8.663943      0.351730         8.437089    -0.644967

謝謝你的建議,

如果您確定所有month_list都在索引中,則可以執行df.loc[month_list] ,否則可以使用reindex

df.reindex(pd.to_datetime(month_list))

輸出:

            month  mean_mon_flow  std_mon_flow  monthly_flow_ln  std_anomaly
date                                                                        
1950-08-01      8       8.614236      0.310865         8.173776    -1.416887
1950-09-01      9       8.663943      0.351730         8.437089    -0.644967

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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