Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/svn/5.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 如何对数据帧中的行执行基本算术运算?_Python_Python 3.x_Pandas - Fatal编程技术网

Python 如何对数据帧中的行执行基本算术运算?

Python 如何对数据帧中的行执行基本算术运算?,python,python-3.x,pandas,Python,Python 3.x,Pandas,我正在试图弄清楚我需要学习什么来执行以下行操作。我简化了一切,以最好地表达我正试图实现的目标 我的最终目标是为数据帧中的每一行从不同列中的前一行中减去一个值 假设我有以下数据帧: Date Open High Low Close Difference 0 2014-07-14 197.61 197.86 197.44 197.60 1 2014-07-15 197.72 198.10 196.36 197.

我正在试图弄清楚我需要学习什么来执行以下行操作。我简化了一切,以最好地表达我正试图实现的目标

我的最终目标是为数据帧中的每一行从不同列中的前一行中减去一个值

假设我有以下数据帧:

    Date        Open    High    Low     Close   Difference
0   2014-07-14  197.61  197.86  197.44  197.60          
1   2014-07-15  197.72  198.10  196.36  197.23          
2   2014-07-16  198.11  198.26  197.42  197.96  
我想计算差分列,计算公式如下:

Open(n) - Close(n-1)  : where n is the current day. 
所以我从今天的开盘价中减去昨天的收盘价

它应该输出到:

Difference
NaN
0.12
0.88

我不确定我应该熟悉什么样的操作才能理解如何做到这一点。我已经掌握了将列相乘的诀窍,并使用它们进行基本操作

您只需从
打开
中减去移位版本的
关闭
,就可以:

df.Open.sub(df.Close.shift()).rename('Difference')

0     NaN
1    0.12
2    0.88
Name: Difference, dtype: float64

您只需从
打开
中减去移位版本的
关闭
,就可以得到:

df.Open.sub(df.Close.shift()).rename('Difference')

0     NaN
1    0.12
2    0.88
Name: Difference, dtype: float64

我试着使用移位函数。如果需要,请使用groupby:

import pandas as pd
Data = {'Date':  ['2014-07-14', '2014-07-15','2014-07-16'],
        'Open': [197.61, 197.72,198.11],
        'High': [197.86,198.10,198.26],
        'Low':[197.44,196.36 ,197.42],
        'Close': [197.60 ,197.23,197.96 ]
        }

df = pd.DataFrame(Data, columns = ['Date','Open','High','Low','Close'])
df['Difference']=df['Open']-df['Close'].shift(1)

我试着使用移位函数。如果需要,请使用groupby:

import pandas as pd
Data = {'Date':  ['2014-07-14', '2014-07-15','2014-07-16'],
        'Open': [197.61, 197.72,198.11],
        'High': [197.86,198.10,198.26],
        'Low':[197.44,196.36 ,197.42],
        'Close': [197.60 ,197.23,197.96 ]
        }

df = pd.DataFrame(Data, columns = ['Date','Open','High','Low','Close'])
df['Difference']=df['Open']-df['Close'].shift(1)

换档功能为您完成此项工作! 使用
shift(1)
并作为名为“difference”的新列附加到
df
。函数中的参数指示要用于成对减法的步长

diff=df['Open']-df['Close'].shift(1)

df['difference']=diffs

移位功能为您完成这项工作! 使用
shift(1)
并作为名为“difference”的新列附加到
df
。函数中的参数指示要用于成对减法的步长

diff=df['Open']-df['Close'].shift(1)
df['difference']=diff