Reputation: 361
I'm trying to change values for lat and long using postal codes as key in a main dataframe. The problem is because of the main df I only need to replace those records for lat and long where the state is Arizona.
And the second df which is the substitute only have postal code, lat and long columns, so I've to use Postal codes as key.
If I want to replace all values I can use this function:
origin.loc[origin['Postal Code'].isin(sustitute['Postal Code']),
['Latitude', 'Longtiude']] = sustitute[['Latitude_ex', 'Longitude_ex']]
But I don't know how to put the condition for the state, so I use the next part to do it, but I want a more pythonic way to do this:
ari = codigos_cp.query("State == 'Arizona'").copy()
ari = pd.merge(ari , cp_sust, how='left', on='Postal Code')
Upvotes: 0
Views: 44
Reputation: 66
You can use numpy.where to make the condition
import numpy as np
origin['Latitude'] = np.where(origin['State'] == 'Arizona', substitute['Latitude_ex'], origin['Latitude'])
origin['Longitude'] = np.where(origin['State'] == 'Arizona', substitute['Longitude_ex'], origin['Longitude'])
Upvotes: 1