Skip to main content
 首页 » 编程设计

Python pandas dataframe 1 非零和非 NaN 属性每 n 行

2024年10月17日10jiqing9006

我有一个按以下方式定义的 Pandas 数据框:

2009-11-18  500.0 
2009-11-19  500.0 
2009-11-20    NaN 
2009-11-23  500.0 
2009-11-24  500.0 
2009-11-25    NaN 
2009-11-27    NaN 
2009-11-30    NaN 
2009-12-01  500.0 
2009-12-02  500.0 
2009-12-03  500.0 
2009-12-04  500.0 
2009-12-07    NaN 
2009-12-08    NaN 
2009-12-09  500.0 
2009-12-10  500.0 
2009-12-11  500.0 
2009-12-14  500.0 

我的意图是每 n 行保留一个非 NaN 元素。例如,如果我的 n 是 4,我会保留 2009-11-18 500,并将 2009-11-23 之前(包括)的所有其他设置为 0,我会对数组的其他元素重复相同的操作,是否有一个有效的,执行此操作的 pythonic,矢量化方式?

为了使这个更具体,我打算在数组上最终看起来像这样:

2009-11-18  500.0 
2009-11-19  0 
2009-11-20  0 
2009-11-23  0 
2009-11-24  500.0 
2009-11-25  0 
2009-11-27  0 
2009-11-30  0 
2009-12-01  500.0 
2009-12-02  0 
2009-12-03  0 
2009-12-04  0 
2009-12-07  0 
2009-12-08  0 
2009-12-09  500.0 
2009-12-10  0 
2009-12-11  0 
2009-12-14  0 

请您参考如下方法:

我想你可以先使用 np.arange 和 floor divison 来创建组,然后是 groupby并通过 idxmax 获取第一个非 NaN 值的索引.最后通过 where 获得 0如果不包含 a 的值:

print (np.arange(len(df.index)) // 4) 
[0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4] 
 
idx = df.col.groupby([np.arange(len(df.index)) // 4]).idxmin() 
print (idx) 
0   2009-11-18 
1   2009-11-24 
2   2009-12-01 
3   2009-12-09 
4   2009-12-11 
Name: col, dtype: datetime64[ns] 
 
df.col = df.col.where(df.index.isin(idx), 0) 
print (df) 
              col 
2009-11-18  500.0 
2009-11-19    0.0 
2009-11-20    0.0 
2009-11-23    0.0 
2009-11-24  500.0 
2009-11-25    0.0 
2009-11-27    0.0 
2009-11-30    0.0 
2009-12-01  500.0 
2009-12-02    0.0 
2009-12-03    0.0 
2009-12-04    0.0 
2009-12-07    0.0 
2009-12-08    0.0 
2009-12-09  500.0 
2009-12-10    0.0 
2009-12-11  500.0 
2009-12-14    0.0 

如果最后一组的长度不是4,最后一个值被省略的解决方案:

arr = np.arange(len(df.index)) // 4 
print (arr) 
[0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4] 
 
#if equal by last value of array substract 1 
arr1 = np.where(arr == arr[-1], arr[-1] - 1, arr) 
print (arr1) 
[0 0 0 0 1 1 1 1 2 2 2 2 3 3 3 3 3 3] 
 
idx = df.col.groupby(arr1).idxmin() 
print (idx) 
0   2009-11-18 
1   2009-11-24 
2   2009-12-01 
3   2009-12-09 
Name: col, dtype: datetime64[ns] 
df.col = df.col.where(df.index.isin(idx), 0) 
print (df) 
              col 
2009-11-18  500.0 
2009-11-19    0.0 
2009-11-20    0.0 
2009-11-23    0.0 
2009-11-24  500.0 
2009-11-25    0.0 
2009-11-27    0.0 
2009-11-30    0.0 
2009-12-01  500.0 
2009-12-02    0.0 
2009-12-03    0.0 
2009-12-04    0.0 
2009-12-07    0.0 
2009-12-08    0.0 
2009-12-09  500.0 
2009-12-10    0.0 
2009-12-11    0.0 
2009-12-14    0.0