I have a data frame like this:
df1
col1 col2 col3
A 11 RS
B 23 PN
A 24 LR
C 23 TN
D 1 WB
C 23 PR
another data frame:
df2
name min max points
A 1 15 1
A 15 30 2
B 1 15 1
B 15 30 2
C 1 15 1
C 15 30 2
D 1 15 1
D 15 30 2
I want to put points values from df2 to df1 if the col2 values of df1 falls under the max value and min values of df2
The data frame I am looking for
df3
col1 col2 col3 points
A 11 RS 1
B 23 PN 2
A 24 LR 2
C 23 TN 2
D 1 WB 1
C 23 PR 2
How to do it in most efficient using pandas
Use merge
first and then filter by boolean indexing
with between
:
df = df1.merge(df2, left_on='col1', right_on='name')
df = df[df['col2'].between(df['min'], df['max'])].drop(['name','min','max'], axis=1)
print (df)
col1 col2 col3 points
0 A 11 RS 1
3 A 24 LR 2
5 B 23 PN 2
7 C 23 TN 2
9 C 23 PR 2
10 D 1 WB 1
Solution for add column points
:
df = df1.reset_index().merge(df2, left_on='col1', right_on='name')
df = df.loc[df['col2'].between(df['min'], df['max']),['index','points']]
print (df)
index points
0 0 1
3 2 2
5 1 2
7 3 2
9 5 2
10 4 1
df1['points'] = df.set_index('index')['points']
print (df1)
col1 col2 col3 points
0 A 11 RS 1
1 B 23 PN 2
2 A 24 LR 2
3 C 23 TN 2
4 D 1 WB 1
5 C 23 PR 2
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.