跨行和跨列计算

2024-04-26 11:19:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pandas dataframe,我需要添加一个引用上一行的计算列。在

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

示例:

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函数,但我看不出它能正常工作。在

^{pr2}$

谢谢你的建议。在


Tags: columns示例dataframepandasdfindexdiffprice
3条回答

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

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)

这是这段代码的输出-

^{pr2}$

这里有一些简单易懂的东西。在

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)

这里假设ask最初为0

^{pr2}$

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

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

相关问题 更多 >