python select case
时间: 2023-10-12 21:06:27 浏览: 44
Python 中没有 select case 语句,但可以使用字典来模拟类似的功能。例如:
```
def func1():
print("This is function 1")
def func2():
print("This is function 2")
def func3():
print("This is function 3")
switcher = {
1: func1,
2: func2,
3: func3
}
case = 2
switcher[case]()
```
输出:
```
This is function 2
```
相关问题
使用Python的Pandas实现Case When语句
在Pandas中,可以使用np.select()函数来实现类似于SQL中的Case When语句。具体实现步骤如下:
1. 导入必要的库
```python
import pandas as pd
import numpy as np
```
2. 定义条件和结果
```python
conditions = [
df['column1'] > 0,
df['column2'] == 'value1',
df['column3'].isin(['value2', 'value3'])
]
results = [
'positive',
'match',
'in_list'
]
```
3. 使用np.select()函数进行条件判断
```python
df['new_column'] = np.select(conditions, results, default='other')
```
以上代码将会在df中新增一个名为"new_column"的列,根据条件判断结果赋予相应的值。
其中,第一个参数为条件列表,第二个参数为结果列表,default参数为默认值(即所有条件都不满足时的返回值)。在条件列表和结果列表中,每个元素的位置是对应的,即第一个条件对应第一个结果,第二个条件对应第二个结果,以此类推。
需要注意的是,条件列表中的每个元素都应该返回一个布尔值,表示该条件是否满足。结果列表中的每个元素可以是任何类型的值,表示该条件满足时需要返回的结果。
使用Python的Pandas实现Case When语句。
在Python的Pandas中,可以使用np.select()方法来实现类似SQL中的Case When语句。下面是一个示例代码:
```python
import pandas as pd
import numpy as np
df = pd.DataFrame({'value': [1, 2, 3, 4, 5]})
conditions = [
df['value'] < 3,
df['value'] >= 3
]
choices = [
'small',
'large'
]
df['category'] = np.select(conditions, choices, default='unknown')
print(df)
```
在上面的示例中,我们创建了一个包含`value`列的DataFrame,并根据条件`value<3`和`value>=3`分别赋值为`small`和`large`,最后将结果存储在新的`category`列中。如果条件不匹配,则使用默认值`unknown`。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![chm](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)