【问题标题】:How to replace values that are less than 0 in multiple columns in Pandas? [duplicate]如何替换 Pandas 多列中小于 0 的值? [复制]
【发布时间】:2021-04-14 14:37:17
【问题描述】:

我正在尝试用 0 的值替换我的数据框中的所有值(对于特定列)< 0

我已经尝试过这段代码,但它似乎对我不起作用:

df.loc[df[['col_1','col_2','col_3']] < 0, 'col_1','col_2','col_3'] = 0

使用这行代码时,出现以下错误:

AttributeError: 'int' object has no attribute 'loc'

我不确定是否是我正在使用的代码阻止我完成我想做的事情。

因此,有人能指出我正确的方向吗?

谢谢 - 请参阅下面的示例数据和预期输出。

样本数据:

col_1     col_2     col_3
--------------------------
  4         5        -1 
 -3        -4         5
  2        -2         2

预期结果:

col_1     col_2     col_3
--------------------------
  4         5         0
  0         0         5
  2         0         2

【问题讨论】:

  • df.loc[...] 给你“'int' 对象没有属性'loc'”时,这意味着df 在代码运行时是一个int。你检查过df吗?

标签: python pandas dataframe


【解决方案1】:

您可以使用pd.DataFrame.clip 将所有低于 0 的值设置为 0(或您选择的阈值):

df[['col_1','col_2','col_3']] = df[['col_1','col_2','col_3']].clip(lower = 0)

根据您的示例数据,这给出了:

In [45]: df
Out[45]: 
   col_1  col_2  col_3
0      4      5     -1
1     -3     -4      5
2      2     -2      2

In [46]: df[['col_1','col_2','col_3']] = df[['col_1','col_2','col_3']].clip(lower = 0)

In [47]: df
Out[47]: 
   col_1  col_2  col_3
0      4      5      0
1      0      0      5
2      2      0      2

【讨论】:

  • 感谢您的解决方案 - 但如果我有超过 30 列,并且我只想将此方法用于 3/36 列,那么最有效的方法是什么?
  • 我也这么认为:只包含 3/36 列的列表,而不是所有列。例如,在您的数据框中,如果您只想剪辑 col_1col_3,而其余部分保持不变,您可以:df[['col_1', 'col_3']] = df[['col_1', 'col_3']].clip(lower=0)
  • 非常感谢您的帮助!非常有帮助,谢谢。 :)
猜你喜欢
  • 2023-03-16
  • 2016-03-29
  • 2016-04-24
  • 1970-01-01
  • 2019-07-04
  • 1970-01-01
  • 2019-09-07
  • 2020-10-15
  • 1970-01-01
相关资源
最近更新 更多