假设我有一个像这样的DataFrame(df):
A B C D
0 0.0000 0.0000 0.0000 0.1234
1 0.0000 -0.9760 -0.5268 -0.4261
2 -0.6277 -1.9284 -1.7718 3.4021
3 0.0000 0.0000 -0.0013 2.2955
4 0.6241 -1.9643 -0.6090 2.0827
我希望从每行中删除前导的0.0000并将NaN作为新“校准”行后面的空白区域,如下所示:
A B C D
0 0.1234 NaN NaN NaN
1 -0.9760 -0.5268 -0.4261 NaN
2 -0.6277 -1.9284 -1.7718 3.4021
3 -0.0013 2.2955 NaN NaN
4 0.6241 -1.9643 -0.6090 2.0827
是否有简单的pandas功能?
答案 0 :(得分:5)
让我们使用mask
,eq
,apply
和dropna
:
df.mask(df.eq(0)).apply(lambda x: pd.Series(x.dropna().values,index=x.index[:len(x.dropna())]),axis=1)
输出:
A B C D
0 0.1234 NaN NaN NaN
1 -0.9760 -0.5268 -0.4261 NaN
2 -0.6277 -1.9284 -1.7718 3.4021
3 -0.0013 2.2955 NaN NaN
4 0.6241 -1.9643 -0.6090 2.0827