Skip to main content
 首页 » 编程设计

python之Pandas :获取列中有效后续帧的第一个和最后一个索引

2024年10月24日8jackei

我有一个包含 nans 的 pandas DataFrame 对象。我想为每一列找到所有后续有效帧的 block ,并从这些 block 中找到第一个和最后一个索引。

示例数据:

[ 
  [ 1,nan], 
  [ 2,nan], 
  [ 3,nan], 
  [ 4,3.0], 
  [ 5,1.0], 
  [ 6,4.0], 
  [ 7,1.0], 
  [ 8,5.0], 
  [ 9,9.0], 
  [10,2.0], 
  [11,nan], 
  [12,nan], 
  [13,6.0], 
  [14,5.0], 
  [15,3.0], 
  [16,5.0] 
] 

其中第一列是索引,第二列是我要过滤的值。结果应该是这样的

[(4,10), (13,16)] 

出于性能原因,我想避免通过 for 循环手动遍历数据...

更新 1:

另外两个标准:

  1. 值列中的有效值不必相等。它们可以采用 -inf 和 +inf 之间的任何有效浮点值

  2. 我只需要有效 block 的第一个和最后一个索引,不需要中间的 NaN block 。

请您参考如下方法:

我认为你可以使用:

#set column names and set index by first column  
df.columns = ['idx', 'a'] 
df = df.set_index('idx') 
#find groups 
df['b'] = (df.a.isnull() != df.a.shift(1).isnull()).cumsum() 
#remove NaN 
df = df[df.a.notnull()].reset_index() 
#aggregate first and last values of column idx   
df = df['idx'].groupby(df.b).agg(['first', 'last']) 
print zip(df['first'], df['last']) 
[(4, 10), (13, 16)] 

然后我尝试修改 cggarvey 的解决方案:

#set column names and set index by first column  
df.columns = ['idx', 'a'] 
df = df.set_index('idx') 
#find edges  
pre =  df['a'] - df['a'].diff(-1) 
pst = df['a'] - df['a'].diff(1) 
a = pre.notnull() & pst.isnull() 
z = pre.isnull() & pst.notnull() 
print zip(a[a].index, z[z].index) 
[(4, 10), (13, 16)]