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

标签 python pandas dataframe

我有一个按以下方式定义的 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/

相关文章:

Python pip如何处理第三方依赖

python - 制作单行数据框

python - groupby 并根据另一列的值保留一列的信息

python - 将两个数据帧与新索引号合并

python - Pandas 从距离矩阵中按 ID 提取列和行

python - 如何使用 df.loc (或其他一些方法)根据特定条件创建新列?

Python os.walk 始终附加 root

python - 我们可以将数组/列表传递给 django 中的模板内容 block 吗? Python

c++ - 将python脚本添加到c++项目

python - 如何仅从时间戳中提取日期?