python-3.x - 如何根据 Pandas 中的其他列根据另一列中的间隔填充缺失值?

标签 python-3.x pandas

假设我有这个df_atm:

     borough          Longitude     Latitude

0    bronx              40.79        -73.78    
1    manhattan          40.78        -73.90
2    staten island      40.84        -73.95
3    NaN                40.57        -74.11

每一行代表 ATM 取款。

我希望根据经度和纬度列内的坐标生成缺失值的值。

     borough          Longitude     Latitude

0    bronx              40.79        -73.78    
1    manhattan          40.78        -73.90
2    staten island      40.84        -73.95
3    staten island      40.57        -74.11

由于坐标 [40.57, -74.11] 位于史坦顿岛的行政区内。

我生成了一个带有行政区坐标的字典:

borough_dict = {"Bronx" : [40.837048, -73.865433], "Brooklyn" : [40.650002, -73.949997], "Manhattan" : [40.758896, -73.985130], "Queens" : [40.742054,-73.769417], "Staten Island" : [40.579021,-74.151535]}

这是我到目前为止所尝试的(代码/伪代码):

df_atm['borough'] = df_atm.apply(
lambda row: **idk what do to here** if np.isnan(row['borough']) else row['borough'],
axis=1
)

提前非常感谢!

最佳答案

试试这个:

from math import cos, asin, sqrt
import pandas as pd

def distance(lat1, lon1, lat2, lon2):
    p = 0.017453292519943295
    a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p)*cos(lat2*p) * (1-cos((lon2-lon1)*p)) / 2
    return 12742 * asin(sqrt(a))

def closest(data, v):
    return min(data, key=lambda p: distance(v[0], v[1], p[0], p[1]))


df = pd.DataFrame(
    [
     {'borough': 'bronx', 'lat': 40.79, 'long': -73.78}, 
     {'borough': 'manhattan', 'lat': 40.78, 'long': -73.90},
     {'borough': None, 'lat': 40.57, 'long': -74.11}
     ],
)


borough_dict = {"Bronx" : [40.837048, -73.865433], "Brooklyn" : [40.650002, -73.949997], "Manhattan" : [40.758896, -73.985130], "Queens" : [40.742054,-73.769417], "Staten Island" : [40.579021,-74.151535]}
boroughs = [(*value, key) for key, value in borough_dict.items()]


df['borough'] = df.apply(
lambda row: closest(boroughs, [row['lat'], row['long']])[2] if row['borough'] is None else row['borough'],
axis=1
)

print(df)

输出:

         borough    lat   long
0          bronx  40.79 -73.78
1      manhattan  40.78 -73.90
2  Staten Island  40.57 -74.11

感谢@trincot answer

关于python-3.x - 如何根据 Pandas 中的其他列根据另一列中的间隔填充缺失值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60468883/

相关文章:

python - 在 Python DataFrame 中如何找出具有有效列值的行数

python - 无法使用 to_json 将 pandas DataFrame 转换为 json

python-3.x - python中多个AGV的最短路径算法

python - 如何使用 BeautifulSoup 发送 key

python - 使用 BeautifulSoup 和 selenium 抓取特定的标签 html

python Pandas : Search for substring in entire dataframe then output the name of the column(s) where the substring was found

python - Pandas 按三列分组,但保留所有其他列

python - 打印整数或带 n 位小数的 float

python - 从文件中获取用户名和密码(Python)

python - 是否有一个函数可以比较两个 DataFrame 并输出不同的元素?