How do I get my variables in this pandas statement?

81 views Asked by At

I'm trying to append new values to a pandas series inside a while loop.

But I'm getting a syntax error on the string formatting...

 import pandas as pd

 sClose = pd.Series()

 close = history['candles'][0]['closeMid']
 time = history['candles'][0]['time']

 sClose = s.Close.append(pd.Series(%s,index=[%s]))% (close, time)

How do i dynamically put new values inside the appended series during each loop?

2

There are 2 answers

0
stellasia On BEST ANSWER

You should use quote around %s.

Something like this would do the trick:

close_str = '%s' % (close, )
time_str = '%s' % (time, )
sClose = sClose.append(pd.Series(close_str,index=[time_str]))

but not sure why you need to transtype to string. If close and time are numbers (or datetime), you can simply do:

sClose = sClose.append(pd.Series(close,index=[time]))
0
Cometsong On

As the %s is only used within quoted strings ('string' formatting), you can use the variable names directly in the final statement instead of putting a meta-variable to hold the place for then.

sClose = s.Close.append(pd.Series(close,index=[time]))