如何使用np.where()添加具有条件的多列

您可以多次使用该条件:

mask = df['contract'] > '0L000099'
df['column1'] = np.where(mask, 1, 2)
df['column2'] = np.where(mask, 3, 4)

或者甚至颠倒条件:

df['column2'] = np.where(~mask, 1, 2)

因为你的问题已经更新了,这里有更新的答案,但是我不确定这是否有用:

import pandas as pd
df = pd.DataFrame({'test':range(0,10)})
mask  = df['test'] > 3
m_len = len(mask)

df['column1'], df['column2'] = np.where([mask, mask], [[1]*m_len, [3]*m_len], [[2]*m_len, [4]*m_len])

   test  column1  column2
0     0        2        4
1     1        2        4
2     2        2        4
3     3        2        4
4     4        1        3
5     5        1        3
6     6        1        3
7     7        1        3
8     8        1        3
9     9        1        3

 问题来源:https://www.5axxw.com/questions/content/44k6g3

posted @ 2022-07-01 14:03  C羽言  阅读(280)  评论(0)    收藏  举报