Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.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_change()从单个数字而不是以前的数字计算变化?_Python_Pandas - Fatal编程技术网

Python:如何使pct_change()从单个数字而不是以前的数字计算变化?

Python:如何使pct_change()从单个数字而不是以前的数字计算变化?,python,pandas,Python,Pandas,我有以下数据: 20.4417 20.5679 20.0826 20.9950 20.0244 19.1702 19.3546 19.1702 19.7138 19.3546 我想计算出第一个值20.4417和其后的每个值之间的百分比变化。pandaspct\u change()函数返回相邻值的变化,当我尝试将序列的第一个值放入pct\u change()时,我认为它将该值作为周期,并给出我的nan。有人知道如何让它接受一个参数,并在该参数和序列的每个元素之间进行百分比变化吗?这是我的密码: s

我有以下数据:

20.4417
20.5679
20.0826
20.9950
20.0244
19.1702
19.3546
19.1702
19.7138
19.3546

我想计算出第一个值
20.4417
和其后的每个值之间的百分比变化。pandas
pct\u change()
函数返回相邻值的变化,当我尝试将序列的第一个值放入
pct\u change()
时,我认为它将该值作为周期,并给出我的
nan
。有人知道如何让它接受一个参数,并在该参数和序列的每个元素之间进行百分比变化吗?这是我的密码:


s2=s1.pct_变化(s1[0])

我想到的第一件事就是添加另一列,然后对轴=1进行百分比变化

import pandas as pd
f = pd.DataFrame(
    [20.4417,
    20.5679,
    20.0826,
    20.9950,
    20.0244,
    19.1702,
    19.3546,
    19.1702,
    19.7138,
    19.3546])

f['added_col'] = [f[0][0] for i in range(len(f))] # Create column where each element is the first item in the first column
f = f[f.columns[::-1]] # flip our columns so we compare in the right order
print f.pct_change(axis=1)[0]
哪些产出:

0    0.000000
1    0.006174
2   -0.017567
3    0.027067
4   -0.020414
5   -0.062201
6   -0.053181
7   -0.062201
8   -0.035609
9   -0.053181
Name: 0, dtype: float64
解决方案
这样就可以了

只写一行数学公式有什么错?
s2 = s1 / s1[0] - 1