简体   繁体   中英

TypeError while formatting pandas.df.pct_change() output to percentage

I'm trying to calculate the daily returns of stock in percentage format from a CSV file by defining a function. Here's my code:

def daily_ret(ticker):
  return f"{df[ticker].pct_change()*100:.2f}%"

When I call the function, I get this error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-40-7122588f1289> in <module>()
----> 1 daily_ret('AAPL')

<ipython-input-39-7dd6285eb14d> in daily_ret(ticker)
      1 def daily_ret(ticker):
----> 2   return f"{df[ticker].pct_change()*100:.2f}%"

TypeError: unsupported format string passed to Series.__format__

Where am I going wrong?

f-strings can't be used to format iterables like that, even Series:

Use map or apply instead:

def daily_ret(ticker):
    return (df[ticker].pct_change() * 100).map("{:.2f}%".format)
def daily_ret(ticker):
    return (df[ticker].pct_change() * 100).apply("{:.2f}%".format)

import numpy as np
import pandas as pd

df = pd.DataFrame({'A': np.arange(1, 6)})

print(daily_ret('A'))
0       nan%
1    100.00%
2     50.00%
3     33.33%
4     25.00%
Name: A, dtype: object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM