【问题标题】:Pandas Use Index to Replace Row Values with ZeroPandas 使用索引将行值替换为零
【发布时间】:2021-06-29 10:05:10
【问题描述】:

我需要从一个数据帧“df”(未显示)应用一个索引,条件是 df 中的行值是否包含 NaN。我发现该索引被称为“rowswithnan”,如下所示是一个系列。我需要使用此索引将不同数据帧“df2”的行值设置为零 (0)。我尝试了很多东西,但遇到了不同的错误。

系列 rowswithnan 索引如下所示:

0   False
1   True
2   True
3   False

df2 看起来像这样:

   plant_name  power_kwh  hour  day  month  year
0  AREC        32963.4    23   31     12    2020
1  AREC        35328.2    22   31     12    2020
2  AREC        37523.6    21   31     12    2020
3  AREC        36446.0    20   31     12    2020

使用“rowswithnan”的索引后,我需要 df2 在“power_kwh”列中替换为“零”:

df2

   plant_name  power_kwh  hour  day  month  year
0  AREC        32963.4    23   31     12    2020
1  AREC        0          22   31     12    2020
2  AREC        0          21   31     12    2020
3  AREC        36446.0    20   31     12    2020

谢谢。

【问题讨论】:

  • df2.loc[rowswithnan, 'power_kwh'] = 0
  • 嗨 - 谢谢,但我使用你的解决方案时遇到了这个错误,我不明白 - ValueError: cannot reindex from a duplicate axis
  • 它应该适用于您的示例数据。改用rowswithnan.values() 试试?
  • 使用 . values() 给了我这个 - TypeError: 'numpy.ndarray' object is not callable
  • 使用rowswithnan.values

标签: pandas indexing rows


【解决方案1】:

由于您有一系列描述 NaN 在数据框中的位置,我猜想有一种更简单的方法来处理整个情况。但是,这是对您在评论中删除系列索引rowswithnan 为 False 的行的请求的回答。

首先将该系列设为数据框的一列:

df['contains_nan'] = `rowswithnan`

然后使用布尔过滤:

df = df.loc[~df.contains_nan]

要将值 power_kwh 设置为零而不是删除行,请执行以下操作:

df.loc[df.contains_nan, 'power_kwh'] = 0

【讨论】:

    猜你喜欢
    • 2014-04-29
    • 2016-10-10
    • 2019-03-22
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 2014-01-29
    相关资源
    最近更新 更多