计算 Pandas DataFrame 中每个滚动的第 n 行之间的百分比变化
Calculate the percent change between every rolling nth row in a Pandas DataFrame
如何计算 Pandas DataFrame 中每个滚动的第 n 行之间的百分比变化?以每第二行为例:
给定以下数据框:
>df = pd.DataFrame({"A":[14, 4, 5, 4, 1, 55],
"B":[5, 2, 54, 3, 2, 32],
"C":[20, 20, 7, 21, 8, 5],
"D":[14, 3, 6, 2, 6, 4]})
我希望生成的 DataFrame 是:
但是,我使用此代码得到的最接近的值:
>df.iloc[::2,:].pct_change(-1)
结果是:
它每隔一行执行一次计算,但这与每第 n 行计算一次滚动 window 不同。我遇到了一个类似的 Stack post 但这个例子不是很简单。
此外,作为奖励,我想将结果输出显示为小数点后两位的百分比。
感谢您的宝贵时间!
知道了!对 'pct_change()'.
使用选项 "periods"
>df.pct_change(periods=-n) #where n=2 for the given example.
如何计算 Pandas DataFrame 中每个滚动的第 n 行之间的百分比变化?以每第二行为例:
给定以下数据框:
>df = pd.DataFrame({"A":[14, 4, 5, 4, 1, 55],
"B":[5, 2, 54, 3, 2, 32],
"C":[20, 20, 7, 21, 8, 5],
"D":[14, 3, 6, 2, 6, 4]})
我希望生成的 DataFrame 是:
但是,我使用此代码得到的最接近的值:
>df.iloc[::2,:].pct_change(-1)
结果是:
它每隔一行执行一次计算,但这与每第 n 行计算一次滚动 window 不同。我遇到了一个类似的 Stack post 但这个例子不是很简单。
此外,作为奖励,我想将结果输出显示为小数点后两位的百分比。
感谢您的宝贵时间!
知道了!对 'pct_change()'.
使用选项 "periods">df.pct_change(periods=-n) #where n=2 for the given example.