【问题标题】:Replacing NaN returns ValueError: Array conditional must be same shape as self替换 NaN 返回 ValueError: 条件数组必须与自身形状相同
【发布时间】:2018-12-10 22:42:40
【问题描述】:

我的目标是使用“填充”(如果它们发生在早上 7 点之前)和“插值”(错误 >= 早上 7 点)来估算错误值(零和负数)。我的“文本”文件包含数千天和数百列。下面是它的一小部分,显示了三天早上 7 点前后都有错误。

date                 a    b    c        
2016-03-02 06:55:00  0.0  1.0  0.0
2016-03-02 07:00:00  2.0  2.0  0.0
2016-03-02 07:55:00  3.0  0.0  3.0
2016-03-03 06:10:00 -4.0  4.0  0.0
2016-03-03 07:00:00  5.0  5.0  5.0
2016-03-03 07:05:00  6.0  0.0  6.0
2016-03-03 08:05:00  7.0  0.0  7.0
2016-03-03 17:40:00  8.0  8.0 -8.0
2016-03-04 05:55:00  0.0  9.0  0.0
2016-03-04 06:00:00  0.0  0.0  10.0

当“日期”是一列时,下面another post 中的一小部分代码可以与其他df 完美配合。

df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)

# Change zeros and negatives to NaN
df.replace(0, np.nan, inplace=True)  
df[df < 0] = np.nan                  

# construct Boolean switch series
switch = (df.index - df.index.normalize()) > pd.to_timedelta('07:00:00')

# use numpy.where to differentiate between two scenarios
df.iloc[:, 0:] = df.iloc[:, 0:].interpolate().where(switch, df.iloc[:, 0:].ffill())

但是,当“日期”被索引时,代码返回ValueError: Array conditional must be same shape as self。任何帮助表示赞赏。

【问题讨论】:

    标签: python


    【解决方案1】:

    以下终于解决了我的问题。

    df['date'] = pd.to_datetime(df['date'])
    # don't set column 'date' to index
    
    # Change zeros and negatives to NaN
    df.replace(0, np.nan, inplace=True)  
    df[df.loc[:, df.columns != 'date'] < 0] = np.nan # change negatives to NaN,   
                                                     # but exclude column 'date',   
                                                     # otherwise, column 'date' will be   
                                                     # converted to NaT  
    
    # construct Boolean switch series
    switch = (df['date'] - df['date'].dt.normalize()) > pd.to_timedelta('07:00:00')
    
    # use numpy.where to differentiate between two scenarios
    df.iloc[:, 0:] = df.iloc[:, 0:].interpolate().where(switch, df.iloc[:, 0:].ffill())
    

    感谢@jpp 提出最重要的最后两行here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-04
      • 2019-03-22
      • 2018-09-23
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      • 2021-12-07
      相关资源
      最近更新 更多