【发布时间】:2022-11-24 03:23:20
【问题描述】:
【问题讨论】:
-
请提供一个最小的、可重现的问题示例:stackoverflow.com/help/minimal-reproducible-example 这里不是要求人们为您编写代码的地方。
标签: python pandas dataframe quantitative-finance
【问题讨论】:
标签: python pandas dataframe quantitative-finance
欢迎来到 SO。这应该可行,但您应该阅读如何提出好的问题:
import numpy as np
import pandas as pd
np.random.seed(42)
YearCode = np.arange(1970, 1975)
df = pd.DataFrame(np.random.rand(5, 3), columns = ['VariableCode', 'Region', 'AggValue'])
df['YearCode'] = YearCode
shifted = df['YearCode'].shift(1)
df['logValue'] = df['YearCode']/shifted
df['logValue'] = np.log(df['logValue'])
print(df)
VariableCode Region AggValue YearCode logValue
0 0.374540 0.950714 0.731994 1970 NaN
1 0.598658 0.156019 0.155995 1971 0.000507
2 0.058084 0.866176 0.601115 1972 0.000507
3 0.708073 0.020584 0.969910 1973 0.000507
4 0.832443 0.212339 0.181825 1974 0.000507
这个怎么运作:
本质上,您将“YearCode”移动 1,然后将原始列除以移动后的列。
【讨论】:
np.log 默认为自然对数。如果需要,请更改为np.log10。如果你想在AggValue上做,程序是一样的。仅确保您的数据框根据 YearCode 列进行排序。