如何基于参考Building-ID筛选大型建筑房间数据表?
问题描述
我有一张包含56267行建筑房间信息的大型数据表(table_A),每行对应一个房间,由Room-ID(A列)和Building-ID(B列)标识,一栋建筑包含多个房间,因此表中存在重复的Building-ID。另有一张包含607个指定Building-ID的参考表(table_B),需要从table_A中筛选出属于这些Building-ID的行,且保留重复项。
构造的示例数据集:
table_A = { 'A': [1, 2, 3, 4, 4, 5], 'more stuff': ["yes", 10, 100, 150, 200, 250], 'even_more stuff': ["no", 10, 50, 100, 200, 250], 'B': [2,4] # 此处为构造错误,真实数据中B列应与其他列长度一致 } table_B = { 'B': [2, 4] }
尝试用groupby筛选,构造DataFrame:
table_A_df = pd.DataFrame(table_A, columns=['A','more stuff','even_more stuff','B']) table_B_df = pd.DataFrame(table_B, columns=['B'])
期望筛选结果:
table_A_filtered = { 'A_new': [2, 4, 4], 'more stuff': [10, 150, 200], 'even_more stuff': [10, 100, 200] }
但因table_A中B列长度与其他列不一致,执行table_A_filtered = table_A_df.groupby(["B"])时出现ValueError: All arrays must be of the same length和KeyError: 'B'错误,寻求正确筛选方案。
解决方案
首先修正示例数据的构造错误:真实场景中table_A的每一行(每个房间)都应对应一个Building-ID,因此B列长度必须与其他列一致。修正后的示例table_A如下:
table_A = { 'A': [1, 2, 3, 4, 4, 5], 'more stuff': ["yes", 10, 100, 150, 200, 250], 'even_more stuff': ["no", 10, 50, 100, 200, 250], 'B': [1, 2, 3, 4, 4, 5] # 每个房间对应唯一的Building-ID }
以下是两种高效的筛选方案:
方案一:使用isin()方法(推荐,适配大型数据集)
直接判断table_A的B列值是否存在于table_B的B列中,快速筛选出符合条件的行:
import pandas as pd # 构造正确的DataFrame table_A_df = pd.DataFrame(table_A) table_B_df = pd.DataFrame(table_B) # 获取目标Building-ID列表 target_buildings = table_B_df['B'].tolist() # 筛选数据并重置索引(可选操作) filtered_df = table_A_df[table_A_df['B'].isin(target_buildings)].reset_index(drop=True) # 重命名A列为A_new(按需执行) filtered_df = filtered_df.rename(columns={'A': 'A_new'}) print(filtered_df)
输出结果与期望一致:
A_new more stuff even_more stuff B 0 2 10 10 2 1 4 150 100 4 2 4 200 200 4
方案二:使用merge()方法
通过内连接筛选匹配的行,自动保留重复项,适合需要处理关联数据的场景:
import pandas as pd table_A_df = pd.DataFrame(table_A) table_B_df = pd.DataFrame(table_B) # 内连接,仅保留B列匹配的行 filtered_df = pd.merge(table_A_df, table_B_df, on='B', how='inner') # 重命名A列并调整列顺序(按需执行) filtered_df = filtered_df.rename(columns={'A': 'A_new'})[['A_new', 'more stuff', 'even_more stuff']] print(filtered_df)
内容的提问来源于stack exchange,提问作者Lamine Traore
相关产品推荐
相关产品推荐

