Python Forum
How to map two data frames based on multiple condition
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to map two data frames based on multiple condition
#1
Hi,
I want to map df1 and grep the value from df2 if df1 column1(i.e ID1) value is between df2 column1(ID1) and column2(ID2). I sue below code, but I did not the answer


# importing pandas as pd
import pandas as pd
  
# creating dataframes
df1 = pd.DataFrame({'ID1': [1, 2, 3, 4], 
                    'Name': ['John', 'Tom', 'Simon', 'Jose']})
  
df2 = pd.DataFrame({'ID1': [1, 2, 3, 5],
                    'ID2': [11, 18, 23, 25],
                    'Class': ['A', 'G', 'M', 'D']})
  
# merging df1 and df2 with merge function
#df = pd.merge(df1, df2)
#print(df)
#print("="*15)
df = pd.merge(df2, df1)
#print(df)
print(f'df1:\n{df1}')
print("="*15)
print(f'df2:\n{df2}')

idx= df1.loc[(df1['ID1']>=df2['ID1']) & (df1['ID1']< df2['ID2'])]
print(f'len of index{len(idx)}')
print(f'len of index{idx}')
for example: df1 ['ID1'] is 1 which is between df2 ['ID1] & ['ID2'] 1 &11, so the corresponding value I want to grep is "A"
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 424 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  Better python library to create ER Diagram by using pandas data frames as tables klllmmm 0 1,098 Oct-19-2023, 01:01 PM
Last Post: klllmmm
  Is there a more elegant way to concatenate data frames? db042190 3 918 Jun-13-2023, 05:08 PM
Last Post: snippsat
  Sent email based on if condition stewietopg 1 856 Mar-15-2023, 08:54 AM
Last Post: menator01
  Grouping Data based on 30% bracket purnima1 4 1,191 Mar-10-2023, 07:38 PM
Last Post: deanhystad
  create new column based on condition arvin 12 2,223 Dec-13-2022, 04:53 PM
Last Post: jefsummers
  How to assign a value to pandas dataframe column rows based on a condition klllmmm 0 828 Sep-08-2022, 06:32 AM
Last Post: klllmmm
  Load multiple Jason data in one Data Frame vijays3 6 1,536 Aug-12-2022, 05:17 PM
Last Post: vijays3
  conditionals based on data frame mbrown009 1 893 Aug-12-2022, 08:18 AM
Last Post: Larz60+
  I have written a program that outputs data based on GPS signal kalle 1 1,161 Jul-22-2022, 12:10 AM
Last Post: mcmxl22

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020