0

I have two columns:

           number
apple         2
banana        3
grape         25
cat           4
jelly         1

I need to find unique values that each category contains. This is how you could create a new df

import numpy as np
import pandas as pd    
df = pd.DataFrame({'category':['apple', 'banana', 'grape', 'cat', 'jelly'],
                       'number':[2,3,25,4,1]})

I have this another df which needs to be filled with the value.

category    name number
apple       aliya   2
banana      reeva   3
apple       dev     2
grape       ruby    25
cat         cosmo   4
jelly       jack    1
cat         goldy   4
grape       frr    25
chixcy
  • 51
  • 9

1 Answers1

0

You can apply:

import pandas as pd
df = pd.DataFrame({'category':['apple', 'banana', 'grape', 'cat', 'jelly'],
                       'number':[2,3,25,4,1]})

df2 = pd.DataFrame({'category':['apple', 'banana', 'apple', 'grape', 'cat', 'jelly', 'cat', 'grape'],
                    'name':['a', 'b', 'ple', 'rap', 'ct', 'jly', 't', 'gape']})

new_col = []
for index, row in df2.iterrows():
    new_col.append(df.loc[df['category'] == row['category'], 'number'].values[0])
df2['number'] = new_col
print(df2)

Output:

  category  name  number
0    apple     a       2
1   banana     b       3
2    apple   ple       2
3    grape   rap      25
4      cat    ct       4
5    jelly   jly       1
6      cat     t       4
7    grape  gape      25
David Meu
  • 1,527
  • 9
  • 14
Renaud
  • 2,709
  • 2
  • 9
  • 24