Home > database >  Multiply 2 columns within a DataFrame at different Datetimeindex
Multiply 2 columns within a DataFrame at different Datetimeindex

Time:09-05

I want to multiply 2 columns within the same DataFrame. The multiplication should not be at the same rows and hence at different DatetimeIndexes.

For instance:

a = df2['Column1'].loc['2021-04-26 00:00:00':'2021-04-26 08:00:00']
a

2021-04-26 00:00:00 -32.414135

2021-04-26 02:00:00 -20.799902

2021-04-26 04:00:00 -18.852000

2021-04-26 06:00:00 -18.297503

2021-04-26 08:00:00 -17.214313

b = df2['Column2'].loc['2021-04-26 02:00:00':'2021-04-26 08:00:00']
b```

2021-04-26 02:00:00 -0.358308

2021-04-26 04:00:00 -0.093650

2021-04-26 06:00:00 -0.029413

2021-04-26 08:00:00 -0.059199

As a result I want a new column that will give:

2021-04-26 00:00:00 NaN

2021-04-26 02:00:00 (-32.414135*(-0.358308))

2021-04-26 04:00:00 (-20.799902*(-0.093650))

2021-04-26 06:00:00 (-18.852000*(-0.029413))

2021-04-26 08:00:00 (-18.297503*(-0.059199)) #All as calculated values

CodePudding user response:

Dataframe operations are performed on the same row, as the result needs to be assigned to a specific row index.

What you can do here is to shift the values of one column first and multiply it with the values of the other one.

The following line should give you the result you specify:

df2["Column1"].shift(1) * df2["Column2"]

There are different ways how you can specify the offset for shifting – see the documentation here.

  • Related