Python Pandas,使用 Dataframe 中的先前值 [英] Python Pandas, using the previous value in Dataframe

查看:73
本文介绍了Python Pandas,使用 Dataframe 中的先前值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 b(t-1) 变量的函数,例如:

I have a function that use b(t-1) variable like:

def test_b(a,b_1):
     return a + b_1

假设有以下数据框:

df = pd.DataFrame({'a':[1,2,3],'b':np.nan})

我正在分配 b_1 初始值:

I am assigning the b_1 initial value:

df['b'].ix[0]=0

然后(使用我的 Matlab 经验),我使用循环:

and then (using my Matlab experience), i use the loop:

for i in range(1,len(df)):
    df['b'].ix[i] = test_b(df['a'].ix[i],df['b'].ix[i-1])

输出:

  a|b
0|1|0
1|2|2
2|3|5

这样做是否更优雅?

推荐答案

你永远不想做这样的作业,因为这是 链式索引

You never want to do assignments like this, as this is chained indexing

这是一个循环关系,因此 ATM 以超高性能的方式做到这一点并不容易,但请参阅 这里.

This is a recurrent relation, so not easy way ATM to do this in a super performant manner, though see here.

这里是一个关于此的未决问题,指向this 使用 ifilter 来解决关系.

here is an open issue about this with a pointer to this which uses ifilter to solve the relation.

这篇关于Python Pandas,使用 Dataframe 中的先前值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆