如何基于条件将Pandas DataFrame索引追加至对应空列表
实现步骤
首先我们先对原始DataFrame做预处理,把字符串格式的'NaN'转换为pandas可识别的缺失值,再逐行判断每行三个列的存在状态,按规则归类到对应列表即可。
完整代码
import pandas as pd import numpy as np # 原始数据构造 dictionary = {'Monday': {'John': 5, 'Lisa': 1, 'Karyn': 'NaN', 'steve': 1, 'ryan': 4, 'chris': 5, 'jessie': 6}, 'Friday': {'John': 0, 'Lisa': 1, 'Karyn':'NaN', 'steve': 4, 'ryan': 7, 'chris': 'NaN', 'jessie': 11}, 'Saturday': {'John': 0, 'Lisa': 1, 'Karyn': 2, 'steve': 4, 'ryan': 'NaN', 'chris': 'NaN', 'jessie': 1}} tab = pd.DataFrame(dictionary) # 定义空列表 mon_only = [] fri_only = [] sat_only = [] mon_fri_only = [] mon_sat_only = [] fri_sat_only = [] mon_fri_sat = [] # 预处理:将字符串NaN转为数值缺失值,所有列转为浮点型方便判断 tab = tab.replace('NaN', np.nan).astype(float) # 逐行处理分类 for name, row in tab.iterrows(): # 逐个判断对应列是否满足存在条件:非空且值>0 is_mon = pd.notna(row['Monday']) and row['Monday'] > 0 is_fri = pd.notna(row['Friday']) and row['Friday'] > 0 is_sat = pd.notna(row['Saturday']) and row['Saturday'] > 0 # 按组合匹配对应列表 if is_mon and is_fri and is_sat: mon_fri_sat.append(name) elif is_mon and is_fri: mon_fri_only.append(name) elif is_mon and is_sat: mon_sat_only.append(name) elif is_fri and is_sat: fri_sat_only.append(name) elif is_mon: mon_only.append(name) elif is_fri: fri_only.append(name) elif is_sat: sat_only.append(name) # 打印验证结果 print(f"{mon_only = }") print(f"{fri_only = }") print(f"{sat_only = }") print(f"{mon_fri_only = }") print(f"{mon_sat_only = }") print(f"{fri_sat_only = }") print(f"{mon_fri_sat = }")
输出结果
运行上述代码后输出和预期完全一致:
mon_only = ['John', 'chris'] fri_only = [] sat_only = ['Karyn'] mon_fri_only = ['ryan'] mon_sat_only = [] fri_sat_only = [] mon_fri_sat = ['Lisa', 'steve', 'jessie']
内容的提问来源于stack exchange,提问作者newbzzs
相关产品推荐
相关产品推荐

