0

I have two data frames with different no of rows as below.

my first data frame(df1):

name   value
1000 |  1
633  |  2
1233 |  3
1333 |  1

my second data frame(df2):

min       max 
500    |  999
1000   | 1499
1500   | 1999

my desired output: min and max columns should be added to the df1 by selecting the proper range

name   value    min   max 
1000 |  1    | 1000  | 1499
633  |  2    | 500   | 999
1233 |  3    | 1000  | 1499
1333 |  1    | 1000  | 1499

how can I code this using python

Chris
  • 29,127
  • 3
  • 28
  • 51
  • specifications are not clear, do you just want to concat? in that case df2 = pd.concat([df1, df2]) but if you have a different number of rows, you should use pd.merge, the problem is that you didn't gave a merge column. – Ziur Olpa Oct 05 '22 at 07:11
  • I need to find a range of the df1['name'] matching from df2['min] and df2['max'] and add that matching range to the df1 as the new two columns. I think merge can't do because columns names are different in two dataframes – Madhushika Niroshanee Oct 05 '22 at 07:16
  • @mozway this is just not a simple merge. I believe this is a question of assigning a proper interval to `name` value in `df1` based on `min` and `max` in `df2`. – SomeDude Oct 05 '22 at 07:34

1 Answers1

0

Try this;

df1 = pd.DataFrame({"name":[1000,633,1233,1333],
                   "value":[1,2,3,1]}) 
df2 = pd.DataFrame({"min":[500,1000,1500],
                   "max":[999,1499,1999]})

lst_min,lst_max = [],[]

for name in df1["name"]:
    df_temp = df2[(df2["min"] <= name) & (df2["max"] >= name)]
    lst_min.append(df_temp.iloc[0,0])
    lst_max.append(df_temp.iloc[0,1])
    
df1["min"] = lst_min
df1["max"] = lst_max


#output of df1;

   name  value   min   max
0  1000      1  1000  1499
1   633      2   500   999
2  1233      3  1000  1499
3  1333      1  1000  1499
Sachin Kohli
  • 1,956
  • 1
  • 1
  • 6