0

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

halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

0

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)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Thank you, @jezrael, but it caused the following error: ValueError: Cannot remove 1 levels from an index with 1 levels: at least one level must be left. – Need Ynk Mar 04 '22 at 12:47