Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 计算按股息调整的Pct变化_Python_Pandas_Numpy - Fatal编程技术网

Python 计算按股息调整的Pct变化

Python 计算按股息调整的Pct变化,python,pandas,numpy,Python,Pandas,Numpy,我有以下数据: 我需要计算熊猫中的Pct_Change_Adjusted列: Pct变化调整=((值[1]+股息[1])/值[0]-1) 例如,对于第3行、第4行和第5行(Googlesheet),数据为: 2019-01-02 9072 A 1020.0000 0.0000 0.0200 0.0200 9072A 2019-01-03 9072 A 1040.4000 0.0000 0.0200 0.0200 9072A 2019-01-04 9072 A 1009.1880 52.0200

我有以下数据:

我需要计算熊猫中的Pct_Change_Adjusted列:

Pct变化调整=((值[1]+股息[1])/值[0]-1)

例如,对于第3行、第4行和第5行(Googlesheet),数据为:

2019-01-02 9072 A 1020.0000 0.0000 0.0200 0.0200 9072A

2019-01-03 9072 A 1040.4000 0.0000 0.0200 0.0200 9072A

2019-01-04 9072 A 1009.1880 52.0200-0.0300.0200 9072A

调整后的Pct变化(第4行)=(1.040.4000+0.0000)/(1020.0000)-1)=0.0200

调整后的Pct变化(第5行)=(1.009.1880+52.02000)/(1040.4000)-1)=0.0200

有没有一种方法可以通过pct_更改快速实现这一点?(而不是在数据中使用条件进行迭代)

到目前为止,我的Pct_变更代码是:

df.groupby(df[6])[3].pct_change(1)


谢谢大家!

IIUC,最有可能的情况是,您可以执行以下操作:

df['Pct_Change_Adjusted'] = df.groupby(['Fund_ID', 'Fund_Series'], as_index=False) \
                              .apply(lambda x: (x.Value + x.Dividend)/x.Value.shift()-1) \
                              .reset_index(level=0, drop=True)

同样的事情,但更详细:

import numpy as np
import pandas as pd
import io

s = '''
Date    Fund_ID Fund_Series Value   Dividend
2019-01-02 9072 A 1020.0000 0.0000
2019-01-03 9072 A 1040.4000 0.0000
2019-01-04 9072 A 1009.1880 52.0200 
''';

df = pd.read_csv(io.StringIO(s),sep='\s')
print(df)

         Date  Fund_ID Fund_Series     Value  Dividend
0  2019-01-02     9072           A  1020.000      0.00
1  2019-01-03     9072           A  1040.400      0.00
2  2019-01-04     9072           A  1009.188     52.02

df['Pct_Change_Adjusted'] = df.groupby(['Fund_ID', 'Fund_Series'], as_index=False) \
                              .apply(lambda x: (x.Value + x.Dividend)/x.Value.shift()-1) \
                              .reset_index(drop=True).values[0]

print(df)

         Date  Fund_ID Fund_Series     Value  Dividend  Pct_Change_Adjusted
0  2019-01-02     9072           A  1020.000      0.00                  NaN
1  2019-01-03     9072           A  1040.400      0.00                 0.02
2  2019-01-04     9072           A  1009.188     52.02                 0.02