If I have a dataframe like so:
id latitude longitude
a -99 48
b -97 44
c -96 52
and I have a dictionary mapping the ids to new latitude+longitude values
new_lat_lon = { 'a':(-99, 58), 'b':(...), 'c':(...) }
is there a quick and dirty way to use .map to change the latitude/longitude columns at once?
eg
df[['latitude', 'longitude']] = df['id'].map(new_lat_lon)
this doesn't work of course, but if there's a way I'd like to know. I am aware that I can simply separate the dictionary into two separate ones, but I am interested if there is a more compact solution. If I need to modify the dictionary a bit (eg change the tuples to lists or something) that's cool too, as long as it's one dictionary. Thank you!
Using update
pd.DataFrame.from_dict(new_lat_lon,'index').rename(columns={0:'latitude',1:'longitude'})
Out[128]:
latitude longitude
a -99 58
b 1 2
c 2 3
updateddf=pd.DataFrame.from_dict(new_lat_lon,'index').rename(columns={0:'latitude',1:'longitude'})
df=df.set_index('id')
df.update(updateddf)
df.reset_index()
Out[132]:
id latitude longitude
0 a -99 58
1 b 1 2
2 c 2 3
You can also unpack using str.get
vals = df.id.map(d)
df.latitude, df.longitude = vals.str.get(0), vals.str.get(1)
Notice that this works if all values in id
are in d
If they are not, can do
vals =df.id.map(d).fillna(df[['latitude', 'longitude']].agg(tuple,1))
df.latitude, df.longitude = vals.str.get(0), vals.str.get(1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.