Issue
I wrote this code in Jupyter Noteebok where I get live BTC prices from Binance API in a DataFrame and now I want to multiply a variable to the BTC price column to create a new one, named "value".
def prices(crypto,interval,start):
BTC_Owned=float(0.004)
df=client.get_historical_klines(crypto,interval,start) #for Binance API
df=pd.DataFrame(df)
df=df.set_index(0) #set time as index
df.index=pd.to_datetime(df.index, unit='ms') #conversion from unix time
df.index.names=['Time']
df=df.iloc[:,:1]
df.columns=['BTC_Price']
df['value']=BTC_Owned * df['BTC_Price']
df=df.astype('float64')
#return type(df['BTC_Price']) #pandas.core.series.Series
return df
The error message I get:
TypeError: can't multiply sequence by non-int of type 'float'.
I already tried other ways of multiplication and get the same error.
Please help.
Solution
Here's what's probably happening:
BTC_Owned=float(0.004)
import pandas as pd
print("\nTry with BTC_Price values of type float:")
df=pd.DataFrame({'value':[1,2,3], 'BTC_Price':[100.0,200.0,300.0]})
df['value'] = BTC_Owned * df['BTC_Price']
print(df)
print("\nTry with BTC_Price values of type string converted to float:")
df=pd.DataFrame({'value':[1,2,3], 'BTC_Price':['100.0','200.0','300.0']})
df['value'] = BTC_Owned * df['BTC_Price'].astype(float)
print(df)
print("\nTry with BTC_Price values of type string (unconverted):")
df=pd.DataFrame({'value':[1,2,3], 'BTC_Price':['100.0','200.0','300.0']})
df['value'] = BTC_Owned * df['BTC_Price']
print(df)
The first one works.
The second one works (and probably shows how to fix your error using astype(float)
).
The third one gives the error you're getting when it tries to multiply a string Series by a float.
Answered By - constantstranger
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.