Pietro Speroni
Pietro Speroni

Reputation: 3221

How to add a column in pandas with values taken from another dataframe

I have two dataframes, df1 and df2. df1 has 2 columns 'Name' and 'K'. df2 has 3 columns 'A', 'B', 'C'

The values of the column B are the same values of df1 'Name'. But now I need to add the column K.

So I tried

for t in range(len(df1)):
        whichvalue=t
        a=df1.iloc[whichvalue,:]
        Name=a['Name']

        knownetf=df2['B'].value_counts()[Name]
        etfs.loc(df2['B']==Name)['K']=a['K']

But this does not seem to work What is a good pythonic way of doing it?

(I am new to Pandas)

Upvotes: 0

Views: 45

Answers (1)

jpp
jpp

Reputation: 164623

You can simply assign as follows:

s = df1.set_index('Name')['K']
df2['K'] = df2['B'].map(s)

The reason this works is because pd.Series.map accepts a series as an input, so we use s in a dictionary-like fashion to map values of 'K' from df1.

Of course, you should check first that the mapping is defined uniquely by 'Name' in df1.

Upvotes: 1

Related Questions