-1

我需要根据同一数据帧的另一个字段中的值在熊猫数据帧中创建一个派生字段。像这样:

def newfield(row):
 If row.col1 == ‘x’
  return ‘value is x’
Elif row.col1 == ‘y’
Return ‘value is y’

然后我称之为:

df.newfield = df.apply(lambda row:newfield(row),axis=1)

有没有办法在没有“申请”的情况下做到这一点?也想让它不那么冗长。Np.where 只允许 2 个条件,但我有超过 2 个。

4

1 回答 1

1

是的,您可以使用np.select

df['newfield'] = np.select([df['col1'] == 'x', df['col1'=='y'],
                           ['value is x', 'value is y'], 
                           np.nan)
于 2021-05-13T02:13:14.480 回答