根据输入在pandas中循环实现多次条件查询
时间: 2024-02-24 12:58:06 浏览: 34
你可以在 Pandas 中使用一个函数来根据输入循环实现多次条件查询。以下是一个示例代码:
```python
import pandas as pd
# 读取数据
df = pd.read_csv('data.csv')
# 定义多个查询条件
conditions = [
{'column': 'age', 'operator': '>', 'value': 30},
{'column': 'gender', 'operator': '==', 'value': 'female'},
{'column': 'income', 'operator': '<', 'value': 50000}
]
# 定义函数实现多次条件查询
def query_dataframe(df, conditions):
# 初始化布尔索引
boolean_index = pd.Series([True] * len(df))
# 循环查询条件,更新布尔索引
for condition in conditions:
column = condition['column']
operator = condition['operator']
value = condition['value']
boolean_index &= df[column].apply(lambda x: eval(f'{x}{operator}{value}'))
# 应用布尔索引,获取查询结果
result = df[boolean_index]
return result
# 获取用户输入的查询条件
user_conditions = []
while True:
column = input('请输入要查询的列名:')
operator = input('请输入要查询的运算符(如 >、<、== 等):')
value = input('请输入要查询的值:')
user_conditions.append({'column': column, 'operator': operator, 'value': value})
go_on = input('是否继续添加查询条件?(输入 y 继续,其它键退出)')
if go_on != 'y':
break
# 调用函数执行查询
result = query_dataframe(df, user_conditions)
# 输出查询结果
print(result)
```
在上面的示例代码中,我们首先读取了一个名为 `data.csv` 的 CSV 文件,然后定义了多个查询条件。接着,我们定义了一个函数 `query_dataframe()` 来实现多次条件查询。该函数接受两个参数,一个是要查询的数据框,另一个是查询条件列表。在函数中,我们使用与之前相同的方法来实现多次条件查询。
接下来,我们使用一个 while 循环来获取用户输入的查询条件。每次循环中,我们使用 input() 函数来获取用户输入的列名、运算符和值,并将它们添加到一个列表中。然后,我们询问用户是否要继续添加查询条件,如果不是则退出循环。
最后,我们调用函数 `query_dataframe()` 来执行查询,并将查询结果输出到控制台。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)