Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.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,我有一个数据帧,其中包含一个列,该列大部分为0,偶尔还包含一些其他整数: In[160]: df.tail(10) Out[160]: alert value 525590 0 46.374 525591 0 46.303 525592 3 46.310 525593 0 46.300 525594 0 46.400 525595 3 46.300 525596 0 46.310 525597 1

我有一个数据帧,其中包含一个列,该列大部分为0,偶尔还包含一些其他整数:

In[160]: df.tail(10)
Out[160]: 
       alert   value
525590     0  46.374
525591     0  46.303
525592     3  46.310
525593     0  46.300
525594     0  46.400
525595     3  46.300
525596     0  46.310
525597     1  46.303
525598     0  46.387
525599     0  46.400
我想添加一个新列,其中包含该列中最后一个非零值的索引:

In[160]: ???.tail(10)
Out[160]: 
       alert   value  change
525590     0  46.374  525585
525591     0  46.303  525585
525592     3  46.310  525592
525593     0  46.300  525592
525594     0  46.400  525592
525595     3  46.300  525595
525596     0  46.310  525595
525597     1  46.303  525597
525598     0  46.387  525597
525599     0  46.400  525597
我知道如何使用显式循环,但我想知道是否有一种更像熊猫的方法来实现这一点。

可以使用

请注意,
NaN
值上升,因为我只使用了最后10项。在运行整个数据集时应该可以

g = df.alert.ne(0)
df.loc[g[g].index, 'change'] = g[g].index
df.ffill()

        alert   value   change
525590  0       46.374  NaN
525591  0       46.303  NaN
525592  3       46.310  525592.0
525593  0       46.300  525592.0
525594  0       46.400  525592.0
525595  3       46.300  525595.0
525596  0       46.310  525595.0
525597  1       46.303  525597.0
525598  0       46.387  525597.0
525599  0       46.400  525597.0