【问题标题】:Add new column with difference of two rows give SettingWithCopyWarning添加具有两行差异的新列给出 SettingWithCopyWarning
【发布时间】:2021-07-30 06:08:45
【问题描述】:

我所拥有的:熊猫数据框中的累计死亡人数。

我需要的是:一个新列,其中包含两行之间的差异值(每天的死亡人数)。所以我做了以下事情:

df_plot.head()

               date     deaths
1153383     2021-05-04  134
1153384     2021-05-03  120
1153385     2021-05-02  120
1153386     2021-04-30  119
1153387     2021-04-29  114

df_plot.set_index('date', inplace=True)
df_plot.sort_index(ascending=False)

df_plot_2 = df_plot['deaths'].shift() - df_plot['deaths']
df_plot['deaths_by_day'] = df_plot_2

但我收到了这条消息。如何以正确的方式创建新列?

ipython-input-46-df83920c83da>:1: SettingWithCopyWarning: 值是 试图在数据帧的切片副本上设置。尝试使用 .loc[row_indexer,col_indexer] = value 而不是

请参阅文档中的注意事项: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy df_plot['deaths_by_day'] = df_plot_2

谢谢。

【问题讨论】:

  • 试试这个:df_plot_2 = (df_plot['deaths'].shift() - df_plot['deaths']).copy()
  • 同样的警告。 :(

标签: python pandas dataframe


【解决方案1】:

在您当前的示例中,.copy() 可用于创建deep copy 并避免使用SettingWithCopyWarning

df['death_diff'] = df['deaths'].shift() - df['deaths'].copy()

想了解更多关于SettingWithCopyWarning

.diff()方法也可以用来获取两行之间的diff

df.set_index('date', inplace=True)
df = df.sort_index(ascending=False)
df['death_diff'] = df.deaths.diff().abs()
df

输出

            deaths  death_diff
date        
2021-05-04  134      NaN
2021-05-03  120      14.0
2021-05-02  120      0.0
2021-04-30  119      1.0
2021-04-29  114      5.0

【讨论】:

  • 第一种方法给出了相同的警告,但第二种方法很好。谢谢。
猜你喜欢
  • 2022-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-28
  • 2022-08-06
相关资源
最近更新 更多