Skip to main content
 首页 » 编程设计

Python Pandas 日期索引

2025年02月15日8TianFang

我正在尝试根据日期(即索引)拆分我的数据框。我的数据如下所示:

  print(df.head()) 
 
  date_time             value   anomaly                          
  2014-11-23 00:00:00   0.414183    0    
  2014-11-23 01:00:00   0.526574    0 
  2014-11-23 02:00:00   0.734324    1 

到目前为止我的代码:

 df_split = df.where(df.index >= '2014-11-23 01:00:00') 

我想要的输出是:

  2014-11-23 01:00:00   0.526574    0 
  2014-11-23 02:00:00   0.734324    1 

我得到的错误是:

  ValueError: Array conditional must be same shape as self 

请您参考如下方法:

你需要boolean indexing :

df_split = df[df.index >= '2014-11-23 01:00:00'] 
print (df_split) 
                        value  anomaly 
date_time                              
2014-11-23 01:00:00  0.526574        0 
2014-11-23 02:00:00  0.734324        1 

如果 DatetimeIndex 中的值已排序使用 loc :

df_split = df.loc['2014-11-23 01:00:00':] 
print (df_split) 
                        value  anomaly 
date_time                              
2014-11-23 01:00:00  0.526574        0 
2014-11-23 02:00:00  0.734324        1 

df_split = df['2014-11-23 01:00:00':] 
print (df_split) 
                        value  anomaly 
date_time                              
2014-11-23 01:00:00  0.526574        0 
2014-11-23 02:00:00  0.734324        1