[英]Pandas Replace column values based on condition upon another column in the same data frame
I have a data frame as below:我有一个数据框如下:
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.如果北距< 90,我想将选择的东距和北距值复制到经度和纬度列,然后将原始值设置为无。
Here is my python code:这是我的 python 代码:
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?有没有更简单的方法来运行上面的操作而不是迭代所有行?
Use pandas.DataFrame.assign
to swap the values of eas/nor and lon/lat with a boolean mask.使用
pandas.DataFrame.assign
将 eas/nor 和 lon/lat 的值与 boolean 掩码交换。
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'])
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.