Python 在条件下,用字符串替换NaN值
我要做的是用字符串'school'替换NaN值。如果经度在114.8到115.2之间,纬度在19.8到20.2之间,则位置列中的NaN值将替换为字符串“School”Python 在条件下,用字符串替换NaN值,python,pandas,dataframe,Python,Pandas,Dataframe,我要做的是用字符串'school'替换NaN值。如果经度在114.8到115.2之间,纬度在19.8到20.2之间,则位置列中的NaN值将替换为字符串“School” df= Date Longitude Latitude Location 0 2020-01-01 01:00 115.1 20.0 NaN 1 2020-01-01 01:01 115.0 20.1 NaN 2 2020-01-0
df=
Date Longitude Latitude Location
0 2020-01-01 01:00 115.1 20.0 NaN
1 2020-01-01 01:01 115.0 20.1 NaN
2 2020-01-01 01:02 114.9 19.9 NaN
3 2020-01-01 01:03 123.1 20.0 NaN
4 2020-01-01 01:04 115.0 18.9 NaN
我想按如下方式转换我的数据帧
df=
Date Longitude Latitude Location
0 2020-01-01 01:00 115.1 20.0 school
1 2020-01-01 01:01 115.0 20.1 school
2 2020-01-01 01:02 114.9 19.9 school
3 2020-01-01 01:03 123.1 20.0 NaN
4 2020-01-01 01:04 115.0 18.9 NaN
我想做的是
df.loc[((df['Longitude']<115.2) & (df['Longitude']>114.8) & (df['Latitude']>19.8) & (df['Latitude']<20.2)), df['Location']]='School'
我不知道为什么会发生这种情况,阅读我的问题真是太多了 你很接近了:
df.loc[((df['Longitude']<115.2) & (df['Longitude']>114.8)
& (df['Latitude']>19.8) & (df['Latitude']<20.2)),
'Location']='School'
尝试使用just numpy where方法:
df['location'] = np.where((df['Longitude'].between(114.8, 115.2)) & ((df['Latitude'].between(19.8, 20.2)), "school", np.nan)
在
df.loc[]
中的条件之后,需要一个列名作为键,并且您正在传递序列df['Location']
,该序列最终导致键错误
仅提及列名,即“Location”
,它将起作用
df.loc[((df['Longitude']<115.2) & (df['Longitude']>114.8) &
(df['Latitude']>19.8) & (df['Latitude']<20.2)),
'Location'] = 'School'
df.loc[(df[‘经度’]114.8)和
(df['Latitude']>19.8)和(df['Latitude']Thx感谢您的帮助!对我有用
df['location'] = np.where((df['Longitude'].between(114.8, 115.2)) & ((df['Latitude'].between(19.8, 20.2)), "school", np.nan)
df.loc[((df['Longitude']<115.2) & (df['Longitude']>114.8) &
(df['Latitude']>19.8) & (df['Latitude']<20.2)),
'Location'] = 'School'