gpt4 book ai didi

python - Pandas 慢。想要在 DataFrame 中第一次出现

转载 作者:太空宇宙 更新时间:2023-11-03 10:56:34 26 4
gpt4 key购买 nike

我有一个包含people 的DataFrame。此 DataFrame 中的一列是 place_id。我还有一个地点 DataFrame,其中一列是 place_id,另一列是 weather。对于每个人,我都试图找到相应的天气。重要的是,许多人都有相同的 place_id

目前,我的设置是这样的:

def place_id_to_weather(pid):
return place_df[place_df['place_id'] == pid]['weather'].item()

person_df['weather'] = person_df['place_id'].map(place_id_to_weather)`

但是这太慢了。我想加快速度。我怀疑我可以实现这样的加速:

不是返回 place_df[...].item(),而是搜索整个列的 place_id == pid 并返回一个系列,并且然后捕获该系列中的第一项,我真的只是想在找到第一个匹配项 place_df['place_id']==pid 后减少 place_df 中的搜索。之后,我就不需要再搜索了。如何将搜索限制为仅首次出现?

我可以使用其他方法来实现这里的加速吗?某种连接类型的方法?

最佳答案

我想你需要drop_duplicatesmerge ,如果两个DataFrames中只有公共(public)列place_idweather,你可以省略参数on(这取决于的数据,也许 on='place_id' 是必要的):

df1 = place_df.drop_duplicates(['place_id'])
print (df1)

print (pd.merge(person_df, df1))

示例数据:

person_df = pd.DataFrame({'place_id':['s','d','f','s','d','f'],
'A':[4,5,6,7,8,9]})
print (person_df)
A place_id
0 4 s
1 5 d
2 6 f
3 7 s
4 8 d
5 9 f

place_df = pd.DataFrame({'place_id':['s','d','f', 's','d','f'],
'weather':['y','e','r', 'h','u','i']})
print (place_df)
place_id weather
0 s y
1 d e
2 f r
3 s h
4 d u
5 f i
def place_id_to_weather(pid):
#for first occurence add iloc[0]
return place_df[place_df['place_id'] == pid]['weather'].iloc[0]

person_df['weather'] = person_df['place_id'].map(place_id_to_weather)
print (person_df)
A place_id weather
0 4 s y
1 5 d e
2 6 f r
3 7 s y
4 8 d e
5 9 f r

#keep='first' is by default, so can be omit
print (place_df.drop_duplicates(['place_id']))
place_id weather
0 s y
1 d e
2 f r

print (pd.merge(person_df, place_df.drop_duplicates(['place_id'])))
A place_id weather
0 4 s y
1 7 s y
2 5 d e
3 8 d e
4 6 f r
5 9 f r

关于python - Pandas 慢。想要在 DataFrame 中第一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39976348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com