gpt4 book ai didi

python - 两列两行滚动的 Pandas Dataframe

转载 作者:太空狗 更新时间:2023-10-30 01:19:21 25 4
gpt4 key购买 nike

我得到了一个包含两列的数据框,其中包含经度和纬度坐标:

将 pandas 导入为 pd

values = {'Latitude': {0: 47.021503365600005,
1: 47.021503365600005,
2: 47.021503365600005,
3: 47.021503365600005,
4: 47.021503365600005,
5: 47.021503365600005},
'Longitude': {0: 15.481974060399999,
1: 15.481974060399999,
2: 15.481974060399999,
3: 15.481974060399999,
4: 15.481974060399999,
5: 15.481974060399999}}

df = pd.DataFrame(values)
df.head()

现在我想在数据帧上应用滚动窗口函数,该函数采用一行和另一行(窗口大小 2)的经度和纬度(两列)来计算半正弦距离。

def haversine_distance(x):
print (x)

df.rolling(2, axis=1).apply(haversine_distance)

我的问题是我从来没有获得 Lng1、Lat1(第一行)和 Lng2、Lat2(第二行)的所有四个值。如果我使用 axis=1,那么我将得到第一行的 Lng1 和 Lat1。如果我使用 axis=0,那么我将得到第一行和第二行的 Lng1 和 Lng2,但只有经度。

如何使用两行两列应用滚动窗口?有点像这样:

def haversine_distance(x):
row1 = x[0]
row2 = x[1]
lng1, lat1 = row1['Longitude'], row1['Latitude']
lng2, lat2 = row2['Longitude'], row2['Latitude']
# do your stuff here
return 1

目前,我正在通过 shift(-1) 将数据帧与其自身连接起来进行此计算,从而在一行中生成所有四个坐标。但是滚动也应该是可能的。另一种选择是将 Lng 和 Lat 合并到一列中,并在其上应用 axis=0 的滚动。但一定有更简单的方法,对吧?

最佳答案

Since pandas v0.23 it is now possible to pass a Series instead of a ndarray to Rolling.apply() .只需设置 raw=False

raw : bool, default None

False : passes each row or column as a Series to the function.

True or None : the passed function will receive ndarray objects instead. If you are just applying a NumPy reduction function this will achieve much better performance. The raw parameter is required and will show a FutureWarning if not passed. In the future raw will default to False.

New in version 0.23.0.

因此,在您给定的示例的基础上,您可以将纬度移动到索引并将整个经度系列(包括索引)传递给您的函数:

df = df.set_index('Latitude')
df['Distance'] = df['Longitude'].rolling(2).apply(haversine_distance, raw=False)

关于python - 两列两行滚动的 Pandas Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47390467/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com