I am trying to fill df with values form a different one.

The first df is:

image description here

The second df is:

image description here

I want to add the column to first df having values from the second one to receive output:

number trans date value
HF01 one sty 1
HF01 one lut 2
- - - -
HF05 five paz 50

I came up with code:

found = []

for index, row in one.iterrows():
    for ind, rw in two.iterrows():
        if ind not in found:
            if (one.loc[index, 'number'] == two.loc[ind, 'number']) & \
               (one.loc[index, 'trans'] == two.loc[ind, 'trans']) & \
                    one.loc[index,'value'] =  two.loc[ind, one.loc[index, 'date']]

It works but it is extremely slow. How it should be done properly?

  • 2
    $\begingroup$ Try to first use pandas.melt to convert the data from wide to long format, then use pandas.merge to join the two tables together to get the output you want. $\endgroup$ – Oxbowerce Jan 26 at 14:21
  • $\begingroup$ Hi, Thank you for the tip. That is what I needed $\endgroup$ – starylass Jan 26 at 16:26

First answers is close, the only thing you need to do is merge both data frames using two fields. You do not need both data frames to have the same length at all


pd.merge(df1, df2, on = ["number","trans"], how = "left")
  • $\begingroup$ Hi, Thank you for looking at it. In this case pandas.melt does the job. I wanted data to be in a long format not wide. $\endgroup$ – starylass Jan 26 at 16:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.