如何删除丢失的数据和 0,同时使用 Pandas 保持数据帧的形状相同?

How to remove missing data and 0s whilst keeping the dataframe the same shape using Pandas?

我有一个数据框,我想重新格式化它,以便它删除在第一个非零值出现在一行中之前是否出现缺失值或零的实例。但是我不想删除任何行或列,也不想删除出现在非零之后的任何 0 或缺失值。

下面是我正在使用的数据框:

> data =[['Adam',2.55,4.53,3.45,2.12,3.14],['Bill',np.NaN,2.14,3.65,4.12],['Chris',np.NaN,0,2.82,0,6.04],['David',np.NaN,0,7.42,3.52]]

> df = pd.DataFrame(data, columns = ['Name', 'A','B','C','D','E'])

此外,这是预期的结果:

> data1 =[['Adam',2.55,4.53,3.45,2.12,3.14],['Bill',2.14,3.65,4.12],['Chris',2.82,0,6.04],['David',7.42,3.52]]

> df1 = pd.DataFrame(data1, columns = ['Name', 'A','B','C','D','E']) 

这不是一个小问题。这是解决方案:

m=df.set_index('Name')
m=m[m.isin(m.mask(m.le(0)).bfill(axis=1).iloc[:,0]).cumsum(axis=1).astype(bool)]
print(m)

         A     B     C     D     E
Name                               
Adam   2.55  4.53  3.45  2.12  3.14
Bill    NaN  2.14  3.65  4.12   NaN
Chris   NaN   NaN  2.82  0.00  6.04
David   NaN   NaN  7.42  3.52   NaN

然后使用:

pd.DataFrame(justify(m.values,np.nan),columns=m.columns,index=m.index).reset_index()

    Name     A     B     C     D     E
0   Adam  2.55  4.53  3.45  2.12  3.14
1   Bill  2.14  3.65  4.12   NaN   NaN
2  Chris  2.82  0.00  6.04   NaN   NaN
3  David  7.42  3.52   NaN   NaN   NaN

解释:

第 1 步:Name 列设置为索引,这样我们就可以只处理数值。 Step2: m.mask(m.le(0)).bfill(axis=1).iloc[:,0] 给出第一个大于 0 的值。 第 3 步: 然后使用 isin() 到 return True 每行中出现值的位置。 Step4: cumsum(axis=1).astype(bool) 使所有剩余的元素都为 True 这样我们就可以只过滤那些值,其他值变为 NaN。 然后使用链接 post.

中的 justify 函数