J_tin
J_tin

Reputation: 11

:unsupported operand type(s) for -: 'str' and 'str'

TypeError: unsupported operand type(s) for -: 'str' and 'str'

face this typeerror msg when I ran the following code:

df_set= pd.read_excel("DATA_SVM.xlsx")

print(df_set.columns)

df1= df_set.drop([0])

df= df1.rename(columns={
    'MSCI World ':'Date',
    'MSCI WORLD U$ - PRICE/BOOK RATIO':'P/B',
    'MSCI WORLD U$ - DIVIDEND YIELD':'YDid',
    'NDDUWI':'Price'})

df['Return']=(df['Price'].shift(-1) - df['Price'])/df['Price']

I am sure it is about the last line. What I want to do is to creat a new column 'return' by using the fomular (price2-price1)/price1.

btw, it can be run by Notebook, but response error in Pycharm.

Anyone providing clues would be appreciated.

Upvotes: 1

Views: 3284

Answers (2)

J_tin
J_tin

Reputation: 11

I found that the following line can work if I input .xlsx instead of csv.

df['Return']=(df['Price'].shift(-1) - df['Price'])/df['Price']

but still try to find out how to make it on a csv. file. I am not sure if .shift function can be used on csv file.

Maybe it's better to change the topic. Is there an alternative function that can achieve: elements of the next row in the same column minus elements of the previous row ?

Upvotes: 0

SimonR
SimonR

Reputation: 1824

It looks like your Price column is formatted as strings. You first need to convert to a type for which subtraction is defined (e.g. float)

df['Price'] = df['Price'].apply(float)

Upvotes: 3

Related Questions