【问题标题】:Numpy where to replace if else, more than 3 arguments in PythonNumpy在哪里替换if else,Python中超过3个参数
【发布时间】:2020-10-23 21:20:05
【问题描述】:
df = {'Fruit':['Apple','Banana','Cherries','Dragonfruit','Elderberry']}
pd.DataFrame(df)

我想根据水果变量创建一个新列。

预期输出:

Fruit             Quantity
Apple                 10
Banana                 5
Cherries               3
Dragonfruit            2
Elderberry             1

代码:

df['Quantity']= np.where(df['Fruit']=='Apple',10, df['Fruit']=='Banana',5,
df['Fruit']=='Cherries',3,df['Fruit']=='Dragonfruit',2,1)
```

shows the error:
TypeError: where() takes from 1 to 3 positional arguments but 9 were given

【问题讨论】:

  • np.select((cond1, cond2), (select1, select2), default)

标签: python pandas numpy dataframe


【解决方案1】:

就像在 cmets 中提到的@Quang,使用 select 函数:

df['Quantity']= np.select((df['Fruit']=='Apple',df['Fruit']=='Banana',df['Fruit']=='Cherries',df['Fruit']=='Dragonfruit'),(10,5,3,2),1) 

输出:

         Fruit  Quantity
0        Apple        10
1       Banana         5
2     Cherries         3
3  Dragonfruit         2
4   Elderberry         1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多