如何从 pandas 数据帧制作标准化系列?
How to make a normalizated series from pandas dataframe?
我有以下代码:
df = pd.DataFrame({
'FR': [4.0405, 4.0963, 4.3149, 4.500],
'GR': [1.7246, 1.7482, 1.8519, 4.100],
'IT': [804.74, 810.01, 860.13, 872.01]},
index=['1980-04-01', '1980-03-01', '1980-02-01', '1980-01-01'])
df = df.iloc[::-1]
df2 = df.pct_change()
df2 = df2.iloc[::-1]
df = df.iloc[::-1]
last=100
serie = []
serie.append(last)
for i in list(df.index.values[::-1][1:]):
last = last*(1+df2['FR'][i])
serie.append(last)
serie
我得到了我所期望的:
[100, 95.88666666666667, 91.02888888888891, 89.7888888888889]
但我正在寻找更简单的方法。
谢谢
试试 cumprod
:
df.iloc[::-1].pct_change().add(1).fillna(1).cumprod()
输出:
FR GR IT
1980-01-01 1.000000 1.000000 1.000000
1980-02-01 0.958867 0.451683 0.986376
1980-03-01 0.910289 0.426390 0.928900
1980-04-01 0.897889 0.420634 0.922856
我有以下代码:
df = pd.DataFrame({
'FR': [4.0405, 4.0963, 4.3149, 4.500],
'GR': [1.7246, 1.7482, 1.8519, 4.100],
'IT': [804.74, 810.01, 860.13, 872.01]},
index=['1980-04-01', '1980-03-01', '1980-02-01', '1980-01-01'])
df = df.iloc[::-1]
df2 = df.pct_change()
df2 = df2.iloc[::-1]
df = df.iloc[::-1]
last=100
serie = []
serie.append(last)
for i in list(df.index.values[::-1][1:]):
last = last*(1+df2['FR'][i])
serie.append(last)
serie
我得到了我所期望的:
[100, 95.88666666666667, 91.02888888888891, 89.7888888888889]
但我正在寻找更简单的方法。
谢谢
试试 cumprod
:
df.iloc[::-1].pct_change().add(1).fillna(1).cumprod()
输出:
FR GR IT
1980-01-01 1.000000 1.000000 1.000000
1980-02-01 0.958867 0.451683 0.986376
1980-03-01 0.910289 0.426390 0.928900
1980-04-01 0.897889 0.420634 0.922856