'How do I return this groupby calculated values back to the dataframe as a single column?

I am new to Pandas. Sorry for using images instead of tables here; I tried to follow the instructions for inserting a table, but I couldn't.

Pandas version: '1.3.2'

Given this dataframe with Close and Volume for stocks, I've managed to calculate OBV, using pandas, like this:

df.groupby('Ticker').apply(lambda x: (np.sign(x['Close'].diff().fillna(0)) * x['Volume']).cumsum())

The above gave me the correct values for OBV as shown here.

However, I'm not able to assign the calculated values to a new column.

I would like to do something like this:

df['OBV'] = df.groupby('Ticker').apply(lambda x: (np.sign(x['Close'].diff().fillna(0)) * x['Volume']).cumsum())

But simply doing the expression above of course will throw us the error:

ValueError: Columns must be same length as key

What am I missing?

How can I insert the calculated values into the original dataframe as a single column, df['OBV'] ?

I've checked this thread so I'm sure I should use apply.

This discussion looked promising, but it is not for my case



Solution 1:[1]

Use Series.droplevel for remove first level of MultiIndex:

df['OBV'] = df.groupby('Ticker').apply(lambda x: (np.sign(x['Close'].diff().fillna(0)) * x['Volume']).cumsum()).droplevel(0)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1