【问题标题】:python pandas changing several columns in dataframe based on one conditionpython pandas根据一个条件更改数据框中的几列
【发布时间】:2018-08-13 15:32:13
【问题描述】:

我是 Python 和 Pandas 的新手。我与 SAS 合作。在 SAS 中,我可以将 IF 语句与“Do; End;”一起使用根据一个条件更新多列的值。
我尝试了 np.where() 子句,但它只更新一列。 “apply(function, ...)”也只更新一列。在函数体内放置额外的更新语句没有帮助。

建议?

【问题讨论】:

  • 你能展示你的df(输入和输出)的样本,以及你尝试过的代码吗?
  • 我要实现: if (): df['col1'] = .... ; df[col2] = ... ; ETC。 。我知道谁用 apply 或 np.where() 分别为每一列做这件事

标签: python pandas


【解决方案1】:

您可以选择要更改的列,然后使用 .apply():

df = pd.DataFrame({'a': [1,2,3], 
                   'b':[4,5,6]})

    a   b
0   1   4
1   2   5
2   3   6


df[['a','b']].apply(lambda x: x+1)

    a   b
0   2   5
1   3   6
2   4   7

这个link 可能会有所帮助:

【讨论】:

  • 感谢您指出我可以将 lambda 应用于多个列。但是,这是非常简单的情况。我想实现: if (): df['col1'] = .... ; df[col2] = ... ; ETC。 。你的
【解决方案2】:

你可以使用:

for col in df:
    df[col] = np.where(df[col] == your_condition, value_if, value_else)

例如:

   a  b
0  0  2
1  2  0
2  1  1
3  2  0

for col in df:
    df[col] = np.where(df[col]==0,12, df[col])

输出:

   a   b
0 12   2
1  2  12
2  1   1
3  2  12

或者,如果您只想将条件应用于某些列,请在 for loop 中选择它们:

for col in ['a','b']:

或者只是这样:

df[['a','b']] = np.where(df[['a','b']]==0,12, df[['a','b']])

【讨论】:

  • 按照你的例子,我希望 df['a'] 像你一样是 12,而 df['b'] 是 25 而不是 12。
  • 那么你可以这样做:df[['a','b']] = np.where(df[['a','b']]==0,[12, 25], df[['a','b']])
  • 谢谢乔,我明白了
  • 不客气,如果对你有帮助,请考虑接受答案:)
猜你喜欢
  • 2020-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-02
  • 2022-01-25
  • 2017-04-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多