我有一个按以下方式定义的 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
和楼层划分来创建组,然后 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
关于Python pandas dataframe 每 n 行 1 个非零和非 NaN 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40838468/