gpt4 book ai didi

python - 两列第一个位置的 NaN(按每个唯一值)

转载 作者:行者123 更新时间:2023-12-01 07:26:11 25 4
gpt4 key购买 nike

我正在尝试将数据帧中每个唯一 ID 的第一个观察结果更改为 NaN。我正在使用时间戳和坐标点的数据帧,这些数据帧已按唯一 ID 和时间戳排序。

示例:

    ID        timestamp   latitude  longitude
0 1 6/9/2017 11:20 38.795333 77.008883
1 1 6/9/2017 13:10 38.889011 77.050061
2 1 6/9/2017 16:23 40.748249 73.984191
3 2 6/11/2017 08:35 38.920602 77.222329
4 2 6/11/2017 10:00 42.366211 71.020943
5 2 6/11/2017 20:00 38.897416 77.036833
6 2 6/12/2017 07:30 38.851426 77.042298
7 2 6/12/2017 10:20 38.917346 77.222553
8 3 6/11/2017 09:01 40.782869 73.967544
9 3 6/11/2017 10:03 38.954268 77.449695
10 3 6/11/2017 11:48 38.872875 77.007763
11 3 6/12/2017 11:52 40.776931 73.876155

尝试:

df['latitude'] =\
df.groupby('ID')['latitude'].apply(lambda x: x[0].np.nan)
df['longitude'] =\
df.groupby('ID')['longitude'].apply(lambda x: x[0].np.nan)

我怀疑虽然df已经分组了,但我仍然需要使用groupby来按每个唯一的ID进行操作。我无法思考如何访问每个第一个值,然后将它们替换为 NaN。

这给出了错误: key 错误:0

这是所需的输出:

        ID        timestamp   latitude  longitude
0 1 6/9/2017 11:20 NaN NaN
1 1 6/9/2017 13:10 38.889011 77.050061
2 1 6/9/2017 16:23 40.748249 73.984191
3 2 6/11/2017 08:35 NaN NaN
4 2 6/11/2017 10:00 42.366211 71.020943
5 2 6/11/2017 20:00 38.897416 77.036833
6 2 6/12/2017 07:30 38.851426 77.042298
7 2 6/12/2017 10:20 38.917346 77.222553
8 3 6/11/2017 09:01 NaN NaN
9 3 6/11/2017 10:03 38.954268 77.449695
10 3 6/11/2017 11:48 38.872875 77.007763
11 3 6/12/2017 11:52 40.776931 73.876155

编辑(为什么这样做?):

我正在尝试改编此版本 this answer to calculate distance and velocity 。一切都很好,除了每个值的每个纬度/经度的第一个值都是错误的,因为该函数在行上计算,不区分 ID。看看不同的解决方案,我怀疑我需要类似 this 的东西...使用 concatshift 计算速度和距离。不过,这对我来说很难概念化 - 所以我认为仅替换这些值会比编辑和重新运行更简单 - 这就是为什么我提出这个问题。

最佳答案

由于您的 df 已按 ID 列排序,因此您可以使用以下技巧将每个唯一 ID 的第一次出现作为 bool 掩码:

mask = df.ID != df.ID.shift()

然后将对应的数据设置为NaN

df.loc[mask, ['latitude', 'longitude']] = np.nan

关于python - 两列第一个位置的 NaN(按每个唯一值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57437165/

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