gpt4 book ai didi

python-3.x - 如何快速在pct_change的结果中添加%?

转载 作者:行者123 更新时间:2023-12-04 01:35:24 26 4
gpt4 key购买 nike

import pandas as pd 
ind = pd.date_range('01/01/2000', periods = 4, freq ='W')
df = pd.DataFrame({"A":[14, 4, 5, 4]},index = ind)

df.pct_change()
A
2000-01-02 NaN
2000-01-09 -0.714286
2000-01-16 0.250000
2000-01-23 -0.200000


我们用pct_change函数得到df的A列增长率,如果我期望以下结果,如何快速在pct_change的输出中增加%?

               A
2000-01-02 NaN
2000-01-09 -71%
2000-01-16 25%
2000-01-23 -20%

最佳答案

您可以尝试以下方法:

import numpy as np
import pandas as pd
ind = pd.date_range('01/01/2000', periods = 4, freq ='W')
df = pd.DataFrame({"A":[None, -0.714286, 0.25, -0.2]},index = ind)

df.loc[~df['A'].isna(), 'A'] = (df.loc[~df['A'].isna(), 'A']*100).astype(int).astype(str) + '%'


df['A']

2000-01-02     NaN
2000-01-09 -71%
2000-01-16 25%
2000-01-23 -20%

关于python-3.x - 如何快速在pct_change的结果中添加%?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59682891/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com