np.where多个返回值

DGr*_*ham 7 python numpy pandas

使用pandas和numpy我正在尝试处理数据框中的列,并希望创建一个包含与之相关的值的新列.因此,如果在列x中存在值1,则在新列中它将是a,对于值2,它将是b等

我可以针对单一条件这样做,即

df['new_col'] = np.where(df['col_1'] == 1, a, n/a)
Run Code Online (Sandbox Code Playgroud)

我可以找到多个条件的例子,即如果x = 3或x = 4,则该值应该是a,但是如果x = 3,则该值应为a,如果x = 4,则该值为c.

我试过简单地运行两行代码,例如:

df['new_col'] = np.where(df['col_1'] == 1, a, n/a)
df['new_col'] = np.where(df['col_1'] == 2, b, n/a)
Run Code Online (Sandbox Code Playgroud)

但显然第二行会覆盖.我错过了一些关键的东西吗

jez*_*ael 11

我想你可以用loc:

df.loc[(df['col_1'] == 1, 'new_col')] = a
df.loc[(df['col_1'] == 2, 'new_col')] = b
Run Code Online (Sandbox Code Playgroud)

要么:

df['new_col'] = np.where(df['col_1'] == 1, a, np.where(df['col_1'] == 2, b, np.nan))
Run Code Online (Sandbox Code Playgroud)