gpt4 book ai didi

python - 从数据帧中的当前索引反向搜索

转载 作者:行者123 更新时间:2023-12-01 07:57:22 27 4
gpt4 key购买 nike

问题陈述:
我有一个像这样的数据框:

   Description      Type      x      y  z
0 Branch Actuated 0 0 0
1 Forward Actuated 7.07 7.07 0
2 Backwards Actuated 7.07 -2.93 0
3 Forward Actuated 17.07 -2.93 0
4 Backwards Actuated 10 -10 0
5 Forward Actuated 17.07 -17.07 0
6 EOL Actuated 7.07 -17.07 0
7 Forward Actuated -7.07 -7.07 0
8 Backwards Actuated -7.07 2.93 0
9 Forward Actuated -17.07 2.93 0
10 Backwards Actuated -10 10 0
11 Forward Actuated -17.07 17.07 0
12 EOL Actuated -7.07 17.07 0
13 Forward Actuated -0 10 0
14 Forward Actuated -0 20 0
15 Forward Actuated 10 0 0

当遇到 EOL 行时,算法需要反向查找第一个 Branch 行并将其插入到 EOL ro 之后,如下所示:

   Description      Type      x      y  z
0 Branch Actuated 0 0 0
1 Forward Actuated 7.07 7.07 0
2 Backwards Actuated 7.07 -2.93 0
3 Forward Actuated 17.07 -2.93 0
4 Backwards Actuated 10 -10 0
5 Forward Actuated 17.07 -17.07 0
6 EOL Actuated 7.07 -17.07 0
0 Branch Actuated 0 0 0 <--
7 Forward Actuated -7.07 -7.07 0
8 Backwards Actuated -7.07 2.93 0
9 Forward Actuated -17.07 2.93 0
10 Backwards Actuated -10 10 0
11 Forward Actuated -17.07 17.07 0
12 EOL Actuated -7.07 17.07 0
0 Branch Actuated 0 0 0 <--
13 Forward Actuated -0 10 0
14 Forward Actuated -0 20 0
15 Forward Actuated 10 0 0

注意:反向搜索应该基于原始数据帧而不是增强数据帧。

问题:如何高效(资源宽松且快速)完成此任务?

最佳答案

使用merge_asof要获取最后匹配的行,请通过 concat 连接在一起, DataFrame.sort_index最后DataFrame.reset_index使用 drop=True 来防止重复的索引值:

df1 = df[df['Description'] == 'Branch']
print (df1)
Description Type x y z
0 Branch Actuated 0.0 0.0 0

df2 = df[df['Description'] == 'EOL']
print (df2)
Description Type x y z
6 EOL Actuated 7.07 -17.07 0
12 EOL Actuated -7.07 17.07 0

df3=pd.merge_asof(df2,df1,left_index=True,right_index=True,suffixes=('_',''))[df1.columns]
print (df3)
Description Type x y z
6 Branch Actuated 0.0 0.0 0
12 Branch Actuated 0.0 0.0 0

df = pd.concat([df, df3]).sort_index().reset_index(drop=True)
<小时/>
print (df)
Description Type x y z
0 Branch Actuated 0.00 0.00 0
1 Forward Actuated 7.07 7.07 0
2 Backwards Actuated 7.07 -2.93 0
3 Forward Actuated 17.07 -2.93 0
4 Backwards Actuated 10.00 -10.00 0
5 Forward Actuated 17.07 -17.07 0
6 EOL Actuated 7.07 -17.07 0
7 Branch Actuated 0.00 0.00 0
8 Forward Actuated -7.07 -7.07 0
9 Backwards Actuated -7.07 2.93 0
10 Forward Actuated -17.07 2.93 0
11 Backwards Actuated -10.00 10.00 0
12 Forward Actuated -17.07 17.07 0
13 EOL Actuated -7.07 17.07 0
14 Branch Actuated 0.00 0.00 0
15 Forward Actuated -0.00 10.00 0
16 Forward Actuated -0.00 20.00 0
17 Forward Actuated 10.00 0.00 0

关于python - 从数据帧中的当前索引反向搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55901916/

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