简体   繁体   中英

Mapping Rows of Two Pandas DataFrames

I'm working with two DataFrames,

df1

altitude
132 16.324794
133 16.027025
134 15.738367
135 15.462613
136 15.195307
137 14.934009
138 14.682448
139 14.440509
140 14.207593
141 14.070644

df2

altitude    density east_wind   north_wind
0   5   0.020567    39.714397   6.795392
1   7   0.016871    41.171996   6.852655
2   9   0.013839    42.629594   6.909918
3   11  0.011351    44.087193   6.967182
4   13  0.009311    45.544791   7.024445
5   15  0.007638    47.003028   7.079618
6   17  0.006263    48.303168   7.340789
7   19  0.005129    48.942837   8.478684
8   21  0.004201    49.588021   9.587021
9   23  0.003433    50.797853   11.256209

I'd like to map the altitude in df1 to the closest altitude in df2 and eventually merging the density east_wind and north_wind values of that row to a new Dataframe.

Expected Result

altitude    density east_wind   north_wind
132 16.324794   0.006263   48.303168   7.340789
136 15.195307   0.007638   47.003028   7.079618
137 14.934009   0.007638   47.003028   7.079618

Please Advise

You could get the closest df2.altitude index using idxmin :

df1['df2_idx'] = df1.altitude.apply(lambda x: df2.altitude.sub(x).abs().idxmin())

#      altitude   df2_idx
# 132  16.324794  6
# 133  16.027025  6
# 134  15.738367  5
# 135  15.462613  5
# 136  15.195307  5
# 137  14.934009  5
# 138  14.682448  5
# 139  14.440509  5
# 140  14.207593  5
# 141  14.070644  5

And then merge on df1.df2_idx and df2.index :

df1.merge(df2.drop('altitude', axis=1), left_on='df2_idx', right_index=True).drop('df2_idx', axis=1)

#      altitude   density   east_wind  north_wind
# 132  16.324794  0.006263  48.303168  7.340789
# 133  16.027025  0.006263  48.303168  7.340789
# 134  15.738367  0.007638  47.003028  7.079618
# 135  15.462613  0.007638  47.003028  7.079618
# 136  15.195307  0.007638  47.003028  7.079618
# 137  14.934009  0.007638  47.003028  7.079618
# 138  14.682448  0.007638  47.003028  7.079618
# 139  14.440509  0.007638  47.003028  7.079618
# 140  14.207593  0.007638  47.003028  7.079618
# 141  14.070644  0.007638  47.003028  7.079618

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM