【问题标题】:Pandas dataframe - Setting with copy warningPandas 数据框 - 设置复制警告
【发布时间】:2020-01-14 16:13:45
【问题描述】:

我想转发一个每小时的数据帧,以便在接下来的几天中,每小时 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。

【问题讨论】:

  • 这通常意味着你的数据框是另一个数据框的一部分。你在某个地方有df = other_df.loc[...] 吗?

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


【解决方案1】:

我执行了您的代码,但没有收到上述警告(其他任何警告都没有)。

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

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

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

【讨论】:

    【解决方案2】:

    这行得通:

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

    与 .loc 非常相似,但不会引发尽可能多的 Settingwithcopy 警告。

    【讨论】:

      猜你喜欢
      • 2018-04-01
      • 2014-04-15
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 2015-05-29
      • 2023-02-03
      • 2015-11-08
      • 1970-01-01
      相关资源
      最近更新 更多