我有一個關于圣保羅租金價格的資料框,但是缺少“緯度”和“經度”的一些值,所以我想用平均值替換“0”。問題是我想用同一地區的平均值替換緯度和經度。
下面是資料幀的一部分。
| 價格 | 公寓 | 尺寸 | 房間 | 洗手間 | 套房 | 停車處 | 電梯 | 帶家具的 | 游泳池 | 新的 | 區 | 協商型別 | 財產種類 | 緯度 | 經度 | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 930 | 220 | 47 | 2 | 2 | 1 | 1 | 0 | 0 | 0 | 0 | 阿圖爾·阿爾維姆/圣保羅 | 租 | 公寓 | -23.543138 | -46.479486 |
| 1 | 1000 | 148 | 45 | 2 | 2 | 1 | 1 | 0 | 0 | 0 | 0 | 阿圖爾·阿爾維姆/圣保羅 | 租 | 公寓 | -23.550239 | -46.480718 |
| 2 | 1000 | 100 | 48 | 2 | 2 | 1 | 1 | 0 | 0 | 0 | 0 | 阿圖爾·阿爾維姆/圣保羅 | 租 | 公寓 | -23.542818 | -46.485665 |
| 3 | 1000 | 200 | 48 | 2 | 2 | 1 | 1 | 0 | 0 | 0 | 0 | 阿圖爾·阿爾維姆/圣保羅 | 租 | 公寓 | -23.547171 | -46.483014 |
| 4 | 1300 | 410 | 55 | 2 | 2 | 1 | 1 | 1 | 0 | 0 | 0 | 阿圖爾·阿爾維姆/圣保羅 | 租 | 公寓 | -23.525025 | -46.482436 |
我該怎么做?
uj5u.com熱心網友回復:
這是一個非常簡單的答案,下面是偽代碼。
for i in range(len(pd.row)):
if pd[i][Latitude] == 0 and pd[i][Longitude] == 0:
//Do replace.
很抱歉我忘記了 pandas 的語法,但我想你可以理解。
uj5u.com熱心網友回復:
首先得到每個地區的平均緯度和經度
df_meanll = df.groupby('District').agg(long_mean=('Longitude','mean'), lat_mean=('Latitude','mean')).reset_index()
替換此處的缺失值,例如:
df = df.merge(df_meanll, on='District', how='left')
填寫缺失值如下:
df.Longitude.fillna(df.long_mean, inplace=True)
df.Latitude.fillna(df.lat_mean, inplace=True)
uj5u.com熱心網友回復:
使用 Pandas 內置函式.groupby、.agg、.assign、.map、.apply
means_mapping = (
df
.groupby("District")
.agg(LongitudeMean=("Longitude", "mean"), LatitudeMean=("Latitude", "mean"))
.reset_index()
).set_index("District").transpose().to_dict("list")
df = df.assign(
Longitude=df["Longitude"].fillna(df["District"].map(means_mapping).apply(lambda x: x[1])),
Latitude=df["Latitude"].fillna(df["District"].map(means_mapping).apply(lambda x: x[0]))
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/513790.html
上一篇:java常用注解校驗引數
下一篇:列沒有出現在熊貓中?
