Ad

Looping Through And Comparing Values In Different Dataframes

- 1 answer

I have two dataframes:

df1:

LowerUpperRank
07first
814second
1523third

df2:

Score
5
3
8
13
20

I want a third result dataframe df3 such that if the score in df2 is between the lower and upper values of df1, that row gets assigned the corresponding rank from df1

ScoreRank
5first
3first
8second
13second
20third
Ad

Answer

Try this.

df1 = pd.DataFrame( [[0,7,'first'],[8,14,'second'],[15,23,'third']], columns = ['Lower', 'Upper', 'Rank'])
df2 = pd.DataFrame( [5,3,8,13,20], columns = ['Score'])

result = []
for index, val in df2.iterrows():
    for id, rank in df1.iterrows():
        if val['Score'] >= rank['Lower'] and val['Score'] <= rank['Upper']:
            result.append(rank['Rank'])
            break

df_result = pd.DataFrame(columns = ['Score','Rank'])
df_result['Score'] = df2['Score']
df_result['Rank'] = result
Ad
source: stackoverflow.com
Ad