跨行和列的熊猫计算

时间:2019-07-06 19:05:24

标签: python pandas

我正在使用pandas数据框,因此需要添加一列并参考上一行进行计算。

我想计算当前行的出价减去上一行的要价。

示例:

df = [[10,100,99],[20,280,300],[30,680,700]   ]
df = pd.DataFrame(df, columns = ['strike_price', 'ask','bid']) 
df = df.set_index('strike_price')

第一行的列将为空。在下一行中将有300 -100,在新行中将有700-280 ...

我尝试使用pandas diff函数,但是我看不到它正常工作。

df.diff(axis=1,periods=1)

谢谢您的任何想法。

3 个答案:

答案 0 :(得分:3)

我认为这个问题需要进一步澄清,但是如果我没记错的话,您正在寻找这个问题-

df['bid']-df['ask'].shift(1)

答案 1 :(得分:0)

这是更容易理解的东西。

import pandas as pd 

df = [[10,100,99],[20,280,300],[30,680,700]   ]
df = pd.DataFrame(df, columns = ['strike_price', 'ask','bid']) 
df = df.set_index('strike_price')

new_bid = []
x = 0
for index, row in df.iterrows():
    y = row['bid']
    new_bid.append(y-x)
    x = row['ask']

df['Final'] = new_bid 
print(df)

这里假设问号最初为0

              ask  bid  Final
strike_price                 
10            100   99     99
20            280  300    200
30            680  700    420

答案 2 :(得分:0)

下面是满足您要求的代码-

import pandas as pd 

df = [[10,100,99],[20,280,300],[30,680,700]   ]
df = pd.DataFrame(df, columns = ['strike_price', 'ask','bid']) 
df = df.set_index('strike_price')

df=df.assign(Derive=df.bid.sub(df.ask.shift(1)))
df['Derive'][10]=""
print(df)

这是这段代码的输出-

              ask  bid Derive
strike_price                 
10            100   99       
20            280  300    200
30            680  700    420
相关问题