【问题标题】:How to change multiples columns with conditional function and other column receive the number 0如何使用条件函数更改多个列,其他列接收数字 0
【发布时间】:2021-11-22 16:45:53
【问题描述】:

我有问题。 5 列具有可变类型(第 2 到 6 列)。如果这些主列 = 0,我需要对应的列(8 到 12)分别看到 0。

df.loc[df['CHT-05'] == 0, 'P CHT-05'] = 0
df.loc[df['CHT-07'] == 0, 'P CHT-07'] = 0
df.loc[df['CHT-09'] == 0, 'P CHT-09'] = 0
df.loc[df['BFR-01'] == 0, 'P BFR-01'] = 0
df.loc[df['JUB-45'] == 0, 'P JUB-45'] = 0

【问题讨论】:

  • 上面带有变量名的代码可以工作,但是我想要一个更短的代码。请帮帮我好吗?
  • 请使用print(df.head().to_string(index=False))的输出更新您的帖子

标签: python pandas for-loop pandas-loc


【解决方案1】:

也许你应该尝试一下:

# your (hardcoded) list 
your_list = ['CHT-05','CHT-07','CHT-09','BFR-01','JUB-45']

for n in your_list:
    df.loc[df[n] == 0, 'P '+str(n)] = 0

【讨论】:

  • 帕斯卡·G·伯纳德,耸人听闻。非常感谢!
  • @VívianAndrade:如果这回答了你的问题,那么请接受它。
猜你喜欢
  • 2018-09-10
  • 2019-03-12
  • 1970-01-01
  • 1970-01-01
  • 2019-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-20
相关资源
最近更新 更多