简体   繁体   English

用以下值填充 DF 的 NaN

[英]Fill NaN of DF with the values below

I have a DF like this, it's a transposed DF ( pd.transpose() ) :我有一个像这样的 DF,它是一个转置的 DF( pd.transpose() ):

         0    1    2
COL_5  NaN  NaN  NaN
COL_4  NaN  NaN    4
COL_3  NaN   12    7
COL_2   15    4   11
COL_1    7    8    9

I want to replace the NaN's with the values below :我想用以下值替换 NaN:

         0    1    2
COL_5   15   12    4
COL_4    7    4    7
COL_3         8   11
COL_2              9
COL_1

I don't know how to do it...我不知道该怎么做...

You can use:您可以使用:

out = (df
   .apply(lambda c: pd.Series(c.dropna().to_numpy()))
   .reindex(range(len(df)))
   .set_axis(df.index)
)

Better alternative if you only have the NaNs at the top and no more afterwards:如果您只有顶部的 NaN 而之后没有更多,则更好的选择:

out = df.apply(lambda c: c.shift(-c.isna().sum()))

output:输出:

          0     1     2
COL_5  15.0  12.0   4.0
COL_4   7.0   4.0   7.0
COL_3   NaN   8.0  11.0
COL_2   NaN   NaN   9.0
COL_1   NaN   NaN   NaN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM