![](/img/trans.png)
[英]Find closest element of a pandas dataframe column in another column's list
[英]How to find the closest element in another column for each element in a column?
情況如下。
我有兩個熊貓數據框:
p1
0 2.910
1 2.885
2 2.875
3 2.855
4 2.910
5 2.870
6 2.850
7 2.875
8 2.865
9 2.875
10 2.890
11 2.910
12 2.965
13 2.955
14 2.935
15 2.905
16 2.900
17 2.905
18 2.970
19 2.940
p2 h
0 2.7 256.88
1 2.8 253.52
2 2.9 250.18
3 3.0 246.86
4 3.1 243.55
目的是首先循環遍歷df1中的所有行,並為每行找到p2中最接近的元素。 例如對於p1[0] = 2.910
,最接近的元素是p2[2] = 2.9
。
回到我們的示例,因此p1[0]
的輸出應為(h[1]+h[3])/2
我希望這一切都說得通,這是我在這里的第一個問題:)。 謝謝!
這是merge_asof
的用法,請注意allow_exact_matches=True
默認為True,例如,在這種情況下,2.9最近值為2.9
df1=df1.sort_values('p1')
s1=pd.merge_asof(df1,df2,left_on='p1',right_on='p2',direction='backward')
s2=pd.merge_asof(df1,df2,left_on='p1',right_on='p2',direction='forward')
df1['Value']=(s1.h+s2.h)/2
使用numpy的另一種解決方案:
import numpy as np
# Generate some test data
x1 = np.random.randint(0,100,10)
x2 = np.vstack([np.random.randint(0,100,10),np.random.normal(0,1,10)]).T
# Repeat the two vectors
X1 = np.tile(x1,(len(x2),1))
X2 = np.tile(x2[:,0],(len(x1),1))
distance = np.abs(X1 - X2.T)
closest_idx = np.argmin(distance,axis=0)
print(x2[closest_idx,1])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.