我认为列表推导式并不是必要的,更好和更快的方法是使用向量化的解决方案,通过使用 布尔索引
进行过滤,并使用 isin
,然后将其转换为列表:
mask = extract['NBN Location Id'].isin(closed['SP Order Location ID'])
cheat_data = extract.loc[mask, ['latitude', 'longitude']].values.tolist()
样例:
closed = pd.DataFrame({'SP Order Location ID':list('ace')})
print (closed)
SP Order Location ID
0 a
1 c
2 e
extract = pd.DataFrame({'NBN Location Id':list('abcde'),
'latitude':['lat1','lat2','lat3','lat4','lat4'],
'longitude':['long1','long2','long3','long4','long4']})
print (extract)
NBN Location Id latitude longitude
0 a lat1 long1
1 b lat2 long2
2 c lat3 long3
3 d lat4 long4
4 e lat4 long4
mask = extract['NBN Location Id'].isin(closed['SP Order Location ID'])
cheat_data = extract.loc[mask, ['latitude', 'longitude']].values.tolist()
print (cheat_data)
[['lat1', 'long1'], ['lat3', 'long3'], ['lat4', 'long4']]
你的解决方案失败了,因为pandas中的
in检查索引值,而不是
Series
的值,所以需要将其转换为列表:
cheat_data = [[row['latitude'],row['longitude']] for index, row in extract.iterrows()
if row['NBN Location Id'] in closed['SP Order Location ID'].tolist()]
print (cheat_data)
[['lat1', 'long1'], ['lat3', 'long3'], ['lat4', 'long4']]
closed = pd.DataFrame({'SP Order Location ID':list('ace')}, index=list('dbw'))
print (closed)
SP Order Location ID
d a
b c
w e
cheat_data = [[row['latitude'],row['longitude']] for index, row in extract.iterrows()
if row['NBN Location Id'] in closed['SP Order Location ID']]
print (cheat_data)
[['lat2', 'long2'], ['lat4', 'long4']]