Home > OS >  Pandas Replace column values based on condition upon another column in the same data frame
Pandas Replace column values based on condition upon another column in the same data frame

Time:09-23

I have a data frame as below:

enter image description here

I want to copy the selected values of easting and northing to the column longitude and latitude if northing is < 90 and then set the original values to None.

Here is my python code:

for i, j in waypoint_df.iterrows():
    easting = j['easting']
    northing = j['northing']
    if northing and northing < 90:
        waypoint_df.at[i,'latitude'] = northing
        waypoint_df.at[i,'longitude'] = easting
        waypoint_df.at[i,'northing'] = None
        waypoint_df.at[i,'easting']= None

Is there a simpler way to run the operation above instead of iterating all rows?

CodePudding user response:

Use pandas.DataFrame.assign to swap the values of eas/nor and lon/lat with a boolean mask.

mask = waypoint_df['northing'].lt(90)

waypoint_df.loc[mask] = waypoint_df.assign(latitude= waypoint_df['easting'], easting= waypoint_df'[latitude'],
                         longitude= waypoint_df['northing'], northing= waypoint_df['longitude'])
# Output :
print(waypoint_df)

   locality_id locality   waypoint   easting   northing                                     description   grid      date collected_by  latitude  longitude  waypoint_pk
0          761     None  BATurnoff  368255.0  6614695.0   Turnoff from Yarri Rd (also access to Harpers  AMG51  12-12-07          SJB       NaN        NaN            1
1          761     None       BKAW  367700.0  6616800.0                End of access track at breakaway  AMG51  12-12-07          SJB       NaN        NaN            2
2          761     None      BKAWT  367071.0  6615492.0   Access track turnoff from Harpers Lagoon road  AMG51  12-12-07          SJB       NaN        NaN            3
3         3581     None    DM14-01       NaN        NaN   King of the Hills dyke -- Hugely contaminated   None  10-11-15       D Mole     121.2     -28.62            4
4         3581     None    DM14-02       NaN        NaN  Intrusion into KOTH dyke? -- Graphic granite -   None  10-11-15       D Mole     121.2     -28.62            5
  • Related