Search code examples
pythonpandasmultiplication

Pandas Python - Multiply every second row from different columns


My data looks as follows:

Column_1     Column_2    Result
17.3604
            7.4342
20.5787
            13.3504
14.9661
            8.85
12.5978
            6.2025
11.7481
            17.9338
...
            ...

How can I multiply the first value of Column_1 with first value of Column_2 and put the result to Result column in the very same row of the Column_2 value so that it looks as follows:

Column_1     Column_2    Result
17.3604
            7.4342       129.0607
20.5787
            13.3504      274.7339
14.9661
            8.85         132.4500
12.5978
            6.2025       78.1379
11.7481
            17.9338      210.6881
...
            ...

I tried: df['Result'] = df.Column_1[0::2] * df.Column_2[1::2] but it didn't work as intended.

Any idea how to do that?


Solution

  • You can try:

    df['Result'] = df.Column_1.ffill()*df.Column_2
    

    Output:

       Column_1  Column_2      Result
    0   17.3604       NaN         NaN
    1       NaN    7.4342  129.060686
    2   20.5787       NaN         NaN
    3       NaN   13.3504  274.733876
    4   14.9661       NaN         NaN
    5       NaN    8.8500  132.449985
    6   12.5978       NaN         NaN
    7       NaN    6.2025   78.137854
    8   11.7481       NaN         NaN
    9       NaN   17.9338  210.688076