OptimusPrime
OptimusPrime

Reputation: 619

multiple list outputs created by a function, how do i put this to a dataframe?

I have the following function

macd, macdsignal, macdhist = talib.MACD(df.Close.values, fastperiod=12, slowperiod=26, signalperiod=9)

I want to make those new values part of my existing dataframe, how can I do that? This is what I tried

 df['macd'], df['macdsignal'], df['macdhist'] = talib.MACD(df.Close.values, fastperiod=12, slowperiod=26, signalperiod=9)

Edit to add a before and after

Before

Close 
10
10 
10 

After

Close    macd    macdsignal    macdhist
10       1.1     3.8           5.7
10       3.2     8.7           4.2   
10       1.9     9.5           1.2

Upvotes: 1

Views: 112

Answers (1)

Abdou
Abdou

Reputation: 13274

Assuming that talib.MACD(df.Close.values, fastperiod=12, slowperiod=26, signalperiod=9) returns a list of lists, you can get the following two things:

Assign the columns to the same dataframe:

lofl = talib.MACD(df.Close.values, fastperiod=12, slowperiod=26, signalperiod=9)
df[['macd', 'macdsignal', 'macdhist']] = pd.DataFrame.from_records(zip(*lofl))

Create a new dataframe with df.assign:

lofl = talib.MACD(df.Close.values, fastperiod=12, slowperiod=26, signalperiod=9)
new_cols = ['macd', 'macdsignal', 'macdhist']
d = {k:v for k,v in zip(new_cols, lofl)}
df = df.assign(**d)

I hope this proves useful.

Upvotes: 1

Related Questions