我有住房地址和邮政编码数据,我想查看它们是否存在于另一个表的另一列中。
我有两个Excel表,分别是表A和表B。我想从表A的第1列(house_address)和第2列(zip)获取每个值,并使用for循环查看该值是否在表B,第1栏(完整地址)。
表A:
住址 | 压缩 |
---|---|
124号房屋 | 12345 |
123家ln | 54321 |
表B:
住址 | 压缩 | property_size | 完整地址 |
---|---|---|---|
124号房屋 | 12345 | 1000 | 124巷12345号 |
123家ln | 54321 | 2000 | 123家ln 54321 |
987草莓rd | 11111 | 3000 | 987草莓rd 11111 |
我的代码是:
# upload tables
table_a = pd.read_excel('table_a.xlsx')
table_b = pd.read_excel('table_b.xlsx')
# create a list from table b and table b of the full_address column for matching purposes
full_address_table_b = list(table_b['full_address'])
# for loop checks if the address is already in my table_B. If it is return the information to # the end user. If it is not then move on to the else statement which will do something else
for i in range(len(table_a)):
# create a concat list of table a full address
full_address_table_a = str(table_a['house_address']) + " " + str(table_b['zip'])
# check if the address is already in our dataset
if table_b.loc[table_b['full_address'].str.contains(full_address_table_a, case=False)]:
# if it is, then just print the info from table b
print(housing_df[housing_df['full_address'] == full_address_test])
# else run another piece of code
else:
print("run this part of the code")
当我运行上面的代码时,出现以下错误:
ValueError:DataFrame的真值不明确。使用a.empty,a.bool(),a.item(),a.any()或a.all()
我想知道是否有人知道我在这里做错了什么。也可能还有一种更有效的方式来创建上述代码,因此,建议您提供更高效的代码。
您可以简单地合并它们以查看哪些值是常见的,如果这是您问题的严重程度:
table_a.merge(table_b, on = ['house_address', 'zip'])
结果是:
house_address zip property_size full_address
0 124 HOUSE LANE 12345 1000 124 HOUSE LANE 12345
1 123 home ln 54321 2000 123 home ln 54321
如果您想具体了解哪些是只在table_a
或table_b
或两者通过一个指标,然后只筛选出基础上,如果需要:
table_a.merge(table_b, on = ['house_address', 'zip'], how = 'outer', indicator = True)
结果是:
house_address zip property_size full_address _merge
0 124 HOUSE LANE 12345 1000 124 HOUSE LANE 12345 both
1 123 home ln 54321 2000 123 home ln 54321 both
2 987 strawberry rd 11111 3000 987 strawberry rd 11111 right_only
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句