Ad
Looping Through And Comparing Values In Different Dataframes
I have two dataframes:
df1:
Lower | Upper | Rank |
---|---|---|
0 | 7 | first |
8 | 14 | second |
15 | 23 | third |
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
Score | Rank |
---|---|
5 | first |
3 | first |
8 | second |
13 | second |
20 | third |
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
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad