熊猫数据框-设置有复制警告

时间:2020-01-14 16:13:45

标签: python-3.x pandas dataframe time-series warnings

我想对一个小时数据帧进行预填充,以便在接下来的几天中为每个小时1对1小时的值进行预填充。每24小时相同。

数据框如下所示:

Timestamp   input1  input2  input3
…   …   …   ..
01.01.2018 00:00    2   5   4
01.01.2018 01:00    3   3   2
01.01.2018 02:00    5   6   1
…           
01.01.2018 22:00    2   0   1
01.01.2018 23:00    5   3   3
02.01.2018 00:00    6   2   5
02.01.2018 01:00    3   6   4
02.01.2018 02:00    3   9   6
02.01.2018 03:00    5   1   7
…           
02.01.2018 23:00    2   5   1
03.01.2018 00:00    NaN NaN NaN
…           
03.01.2018 23:00    NaN NaN NaN

我为此使用了以下代码:

   for hr in range(0,24):    
   df.loc[df.index.hour == hr, Inputs] = df.loc[df.index.hour == hr, Inputs].fillna(method='ffill')

这有效。 不幸的是,我收到警告消息:

\Python\WPy-3670_32bit\python-3.6.7\lib\site-packages\pandas\core\indexing.py:543: SettingWithCopyWarning:  A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
 self.obj[item] = s

我该如何解决,不再收到警告?

生成的df应填充NaN。

2 个答案:

答案 0 :(得分:0)

这有效:

 df[df.index.hour == hr] = df[df.index.hour == hr].fillna(method="ffill")

与.loc非常相似,但不会产生那么多的Settingwithcopy警告。

答案 1 :(得分:0)

我执行了您的代码,但没有收到所提到的警告(没有其他警告)。

使用 loc 是避免此类警告的正确方法(如本消息所述)。

也许您使用的是 Pandas 的旧版本? 如果您使用的是旧版本,请升级到 0.25 ,然后重试。

另一个怀疑:也许此警告与某些 other 指令有关 在您的代码中(没有 loc )?