如何基于多条件筛选Pandas DataFrame?求完整解决方案
设备分类数据筛选完整解决方案
咱们一步步来搞定这个数据筛选需求,先把背景信息理清楚:
1. 原始数据
你提供的设备分类数据如下:
| Base | G | Pref | Sier | Val | Other | latest_class | d_id |
|---|---|---|---|---|---|---|---|
| 0 | 2 | 0 | 0 | 12 | 0 | Val | 38 |
| 12 | 0 | 0 | 0 | 0 | 0 | Base | 39 |
| 0 | 0 | 12 | 0 | 0 | 0 | Pref | 40 |
| 0 | 0 | 0 | 12 | 0 | 0 | Sier | 41 |
| 0 | 0 | 0 | 12 | 0 | 0 | Sier | 42 |
| 12 | 0 | 0 | 0 | 0 | 0 | Base | 43 |
| 0 | 0 | 0 | 0 | 0 | 12 | Other | 45 |
| 0 | 0 | 0 | 0 | 0 | 12 | Other | 46 |
| 0 | 12 | 0 | 0 | 0 | 0 | G | 47 |
| 0 | 0 | 12 | 0 | 0 | 0 | Pref | 48 |
| 0 | 0 | 0 | 0 | 0 | 12 | Other | 51 |
| 0 | 0 | 8 | 5 | 0 | 0 | Sier | 53 |
| 0 | 0 | 0 | 0 | 12 | 0 | Val | 54 |
| 0 | 0 | 0 | 0 | 12 | 0 | Val | 55 |
2. 核心筛选条件
需要满足三个要求:
- 设备在其
latest_class对应的类别中至少连续3个月(即该类别列的数值≥3) - 剔除
latest_class为'Other'的所有记录 - 剔除曾属于多个类别的设备(比如d_id=38同时有G和Val的非零值,属于多类别)
3. 完整实现代码
你已经完成了第一个条件的筛选,现在咱们把另外两个条件补上,整合出完整的代码:
import numpy as np import pandas as pd # 先加载你的数据(如果已经加载好可以跳过这部分) device_class = pd.DataFrame({ 'Base': [0,12,0,0,0,12,0,0,0,0,0,0,0,0], 'G': [2,0,0,0,0,0,0,0,12,0,0,0,0,0], 'Pref': [0,0,12,0,0,0,0,0,0,12,0,8,0,0], 'Sier': [0,0,0,12,12,0,0,0,0,0,0,5,0,0], 'Val': [12,0,0,0,0,0,0,0,0,0,0,0,12,12], 'Other': [0,0,0,0,0,0,12,12,0,0,12,0,0,0], 'latest_class': ['Val','Base','Pref','Sier','Sier','Base','Other','Other','G','Pref','Other','Sier','Val','Val'], 'd_id': [38,39,40,41,42,43,45,46,47,48,51,53,54,55] }) # 条件1:设备在latest_class对应类别中连续≥3个月 i = np.arange(len(device_class)) # 找到每行latest_class对应的列索引 j = (device_class.columns[:-2].values[:, None] == device_class.latest_class.values).argmax(0) cond1 = device_class.values[i,j] >= 3 # 条件2:过滤latest_class为Other的记录 cond2 = device_class['latest_class'] != 'Other' # 条件3:过滤多类别设备(只保留非零类别数为1的设备) # 取前6个分类列,统计每行非零值的数量 cond3 = (device_class.iloc[:, :-2] != 0).sum(axis=1) == 1 # 合并所有条件,得到最终筛选结果 filtered_device = device_class[cond1 & cond2 & cond3] # 输出结果 print(filtered_device)
4. 运行结果
执行上面的代码后,会得到你预期的输出:
| Base | G | Pref | Sier | Val | Other | latest_class | d_id |
|---|---|---|---|---|---|---|---|
| 12 | 0 | 0 | 0 | 0 | 0 | Base | 39 |
| 0 | 0 | 12 | 0 | 0 | 0 | Pref | 40 |
| 0 | 0 | 0 | 12 | 0 | 0 | Sier | 41 |
| 0 | 0 | 0 | 12 | 0 | 0 | Sier | 42 |
| 12 | 0 | 0 | 0 | 0 | 0 | Base | 43 |
| 0 | 12 | 0 | 0 | 0 | 0 | G | 47 |
| 0 | 0 | 12 | 0 | 0 | 0 | Pref | 48 |
| 0 | 0 | 0 | 0 | 12 | 0 | Val | 54 |
| 0 | 0 | 0 | 0 | 12 | 0 | Val | 55 |
内容的提问来源于stack exchange,提问作者Shuvayan Das
相关产品推荐
相关产品推荐

