如果只能在应将其用于pandas数据框后才能声明该列,那么如何计算该列的前一行值?

时间:2018-10-10 15:46:20

标签: python pandas

以下是我拥有的数据框:

import datetime
import pandas as pd
import numpy as np

todays_date = datetime.datetime.now().date()
index = pd.date_range(todays_date-datetime.timedelta(10), periods=10, freq='D')
data = pd.DataFrame(index=index)

data['Open'] = np.random.randint(20,40, size=len(data))
data['High'] = np.random.randint(40,50, size=len(data))
data['Low'] = np.random.randint(10,20, size=len(data))
data['Close'] = np.random.randint(10,20, size=len(data))

我要执行的计算如下:

capital = 30000

data['Shares'] = (capital * 0.05 / data['Close'].shift(1) - data['Low'].shift(1)).round(0)
data['Open_price'] = data['Open'] + 0.5 * (data['High'] - data['Open'])
data['Floating_P/L'] = data['Shares'] * data['Close']
data['Close_price'] = data['Close'] - 0.5 * (data['Close'] - data['Low'])
data['Closed_P/L'] = data['Shares'].shift(1) * data['Close_price']
data['Closed_Balance'] = capital + data['Closed_P/L'].cumsum()
data['Equity'] = data['Closed_Balance'] + data['Floating_P/L']

capital = data['Equity'].shift(1)

如您所见,Equity是根据今天的Shares数字计算得出的,而今天的Equity是根据昨天的capital计算得出的。我想在第一个索引处将Equity设置为Shares的初始值,并根据在第一个索引处的数字计算Shares。从第二个索引开始,Equity应从上移了一行的import { HUB_NAME, HUB_URL } from '../Constants/SignalRConstants'; import { setStarted, setStopped } from '../Actions/StartStopActions'; const $ = window.$; export const signalRStart = (store, callback) => { let hub = $.connection[HUB_NAME]; hub.client.statusChanged = status => { store.dispatch(status === 'Start' ? setStarted() : setStopped()); }; $.connection.hub.url = HUB_URL; $.connection.hub.start(() => callback()); $.connection.hub.disconnected(() => { window.alert('signalr disconnected'); if ($.connection.hub.lastError) { alert('Disconnected. Reason: ' + $.connection.hub.lastError.message); } signalRStart(store, callback); }); }; 开始计算。我该怎么办?

1 个答案:

答案 0 :(得分:0)

在上面给出的代码中,我发现Shares的初始值和Equity的前两个值是Nans,因为计算了Shares的第一个值使用CloseLow列向上移动。假设您可以在此处设置一些值,

尝试这样做?

  1. Equity and Shares

    的数据中创建空列
    data['Equity']=''
    data['Shares']=''
    
  2. capital设置为Equity的初始值。由于您提到了capital = 30000

    的初始值
    capital= 30000
    data['Equity'][0]= 30000 
    
  3. 计算Shares的初始值。在这里尝试为Nans设置值代替Close and Low

    data['Shares'][0]= (capital * 0.05 / data['Close'].shift(1)[0] - data['Low'].shift(1))[0].round(0)
    
  4. 然后使用for循环,该循环从第二个索引迭代到数据长度。