基于PropertyYearBuilt筛选最邻近PipeYear的DataFrame数据
居民区供水项目DataFrame筛选需求
需求说明
需要对居民区供水项目的DataFrame进行子集化筛选,核心规则为:
- 针对每个
PropertyYearBuilt(住宅建成年份),保留两行数据 - 一行对应紧邻且早于该年份的
PipeYear(管道建造年份),且是所有早年管道中最接近住宅年份的 - 另一行对应紧邻且晚于该年份的
PipeYear,且是所有晚年管道中最接近住宅年份的 - 若某个
PropertyYearBuilt不存在符合条件的早年/晚年管道,则该年份的对应行直接排除
原始数据示例
PipeID PricePipe PipeYear PropertyYearBuilt Distance_to_property a 500 2010 2013 1.5 b 600 2007 2008 2.5 c 700 2009 2000 3.0 d 800 1998 1972 4.2 e 900 2003 1980 4.5 f 200 2014 1985 5.0 g 100 2011 1990 5.5 h 850 2018 1995 7.0
期望输出示例
(排除无法匹配到邻近年份的行,如a、h)
PipeID PricePipe PipeYear PropertyYearBuilt Distance_to_property b 600 2007 2008 2.5 c 700 2009 2008 3.0 d 800 1998 2000 4.2 e 900 2003 2000 4.5 f 200 2014 2013 5.0 g 100 2011 2013 5.5
实现方案(基于Pandas)
步骤说明
- 计算每个管道年份与对应住宅年份的差值,区分早于/晚于的情况
- 按
PropertyYearBuilt分组,分别筛选出每个分组中最接近的早年和晚年管道 - 合并筛选结果并整理格式
代码实现
import pandas as pd # 构造原始DataFrame(实际使用时可替换为读取你的数据源) data = { 'PipeID': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], 'PricePipe': [500, 600, 700, 800, 900, 200, 100, 850], 'PipeYear': [2010, 2007, 2009, 1998, 2003, 2014, 2011, 2018], 'PropertyYearBuilt': [2013, 2008, 2000, 1972, 1980, 1985, 1990, 1995], 'Distance_to_property': [1.5, 2.5, 3.0, 4.2, 4.5, 5.0, 5.5, 7.0] } df = pd.DataFrame(data) # 计算年份差值:PipeYear - PropertyYearBuilt df['year_diff'] = df['PipeYear'] - df['PropertyYearBuilt'] # 筛选每个住宅年份对应的最接近早年管道(差值为负,取最大的差值即最接近) earlier_pipes = df[df['year_diff'] < 0].groupby('PropertyYearBuilt').apply( lambda x: x.loc[x['year_diff'].idxmax()] ).reset_index(drop=True) # 筛选每个住宅年份对应的最接近晚年管道(差值为正,取最小的差值即最接近) later_pipes = df[df['year_diff'] > 0].groupby('PropertyYearBuilt').apply( lambda x: x.loc[x['year_diff'].idxmin()] ).reset_index(drop=True) # 合并结果、排序并清理冗余列 result = pd.concat([earlier_pipes, later_pipes])\ .sort_values('PropertyYearBuilt')\ .drop(columns='year_diff')\ .reset_index(drop=True) # 输出结果 print(result)
内容的提问来源于stack exchange,提问作者Xaviermoros
相关产品推荐
相关产品推荐

