Search code examples
pythonconditional-statementsmultiplication

How to multiply columns of different dataframes based on conditions


I have 2 different dataframes, with the first dataframe containing values that I want to multiply with one of the values in the second dataframe, based on a condition.

So let's say my first dataframe contains of a long list with values between 1 and 10, and my second dataframe consists of the values x, y and z. Then I want to multiply the values 1-3 with x, 4-6 with y and 7-10 with z.

How do I accomplish that?

Example input:

df1          df2
1             x
2             y
3             z
4
5
6
7
8
9
10

Desired output:

1x
2x
3x
4y
5y
6y
7z
8z
9z
10z

The actual dataframes are larger than this, but it's just an example.


Solution

  • can you pass your dataframe threw a function somehow like this:

    def newDf(df1, df2):
        df = []
        for idx, i in enumerate(df1):
            if idx <= 2: # 1st condition
                df.append(i * df2[0])
            elif idx <= 5: # 2nd condition
                df.append(i * df2[1])
            else:
                new_df.append(i * df2[2])
    
        return df