gpt4 book ai didi

python - 替换 NaN 返回 ValueError : Array conditional must be same shape as self

转载 作者:太空宇宙 更新时间:2023-11-03 21:28:13 35 4
gpt4 key购买 nike

我的目标是使用“ffill”(如果它们发生在上午 7 点之前)和“interpolate”(对于误差 >= 上午 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:条件数组必须与自身形状相同。如有任何帮助,我们将不胜感激。

最佳答案

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

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 .

关于python - 替换 NaN 返回 ValueError : Array conditional must be same shape as self,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53704978/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com