簡體   English   中英

Pandas條件下用字符串替換NaN值

[英]Pandas replace NaN value by string under conditions

我想要做的是用字符串“學校”替換 NaN 值。 如果經度在 114.8 到 115.2 范圍內,緯度在 19.8 到 20.2 范圍內,則位置列中的 NaN 值將替換為字符串“學校”。

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

我想按如下方式轉換我的 DataFrame

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'

但是,我收到一個錯誤

KeyError: "None of [Float64Index([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan,\n              ...\n              nan, nan, nan, nan, nan, nan, nan, nan, nan, nan],\n             dtype='float64', length=7441)] are in the [columns]"
    

我不確定為什么會發生這種情況,並且非常感謝閱讀我的問題!

你很接近:

df.loc[((df['Longitude']<115.2) & (df['Longitude']>114.8) 
         & (df['Latitude']>19.8) & (df['Latitude']<20.2)), 
      'Location']='School'

此外,您可以between使用:

df.loc[((df['Longitude'].between(114.8, 115.2, inclusive=False) 
         & (df['Latitude'].between(19.8, 20.2, inclusive=False)), 
      'Location']='School'

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'

嘗試僅使用 numpy 方法:

df['location'] = np.where((df['Longitude'].between(114.8, 115.2)) & ((df['Latitude'].between(19.8, 20.2)), "school", np.nan)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM