仅在特定条件下用“-"符号替换 NaN,Python-Pandas [英] replace NaN with '-' sign only in specefic condition ,Python-Pandas

查看:55
本文介绍了仅在特定条件下用“-"符号替换 NaN,Python-Pandas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框

 L1 D1 L2 D2 L31.0 ABC 1.1 4.1 NaNNaN NaN 1.7 NaN NaNNaN 4.1 NaN NaN NaNNaN 1.8 3.2 PQR NaNNaN NaN 1.6 NaN NaN

我想用-"替换所有的 NaN(仅当任何列中的值是该行中的最后一个值时)

所以基本上我想要的输出是

 L1 D1 L2 D2 L31.0 ABC 1.1 4.1 -NaN NaN 1.7 - -NaN 4.1 - - -NaN 1.8 3.2 PQR -NaN NaN 1.6 - -

有人可以帮忙吗,先谢谢了!

解决方案

这是一种方法:

minus_mask = df.loc[:, ::-1].notna().cumsum(axis=1).eq(0)out = df.mask(minus_mask, "-")

我们首先在列上翻转 df 的地方,看看它不是 NaN 的地方,然后取累积和.如果累积和等于 0,那么这些地方就是我们应该放置 "-" 的地方,所以我们使用 mask 方法在那里放置减号,

得到

<预><代码>>>>出去L1 D1 L2 D2 L30 1.0 ABC 1.1 4.1 -1 NaN NaN 1.7 - -2 NaN 4.1 - - -3 NaN 1.8 3.2 PQR -4 NaN NaN 1.6 - -

I have a dataframe

 L1      D1     L2      D2         L3
 1.0    ABC     1.1     4.1        NaN
 NaN    NaN     1.7     NaN        NaN
 NaN    4.1     NaN     NaN        NaN
 NaN    1.8     3.2     PQR        NaN
 NaN    NaN     1.6     NaN        NaN

I want to replace all the NaN with '-' (only when the value in any column is last value in that row)

so basically my desired output will be

 L1      D1      L2      D2         L3
 1.0    ABC     1.1     4.1        -
 NaN    NaN     1.7     -          -
 NaN    4.1      -      -          -
 NaN    1.8     3.2     PQR        -
 NaN    NaN     1.6     -          -

Can someone help, Thank you in advance!

解决方案

Here is one way:

minus_mask = df.loc[:, ::-1].notna().cumsum(axis=1).eq(0)
out = df.mask(minus_mask, "-")

where we first flip the df over the columns, look where it is not NaN and take the cumulative sum. If the cumulative sum equals 0, those places are where we should put "-" so we use mask method to put minus signs there,

to get

>>> out

    L1   D1   L2   D2 L3
0  1.0  ABC  1.1  4.1  -
1  NaN  NaN  1.7    -  -
2  NaN  4.1    -    -  -
3  NaN  1.8  3.2  PQR  -
4  NaN  NaN  1.6    -  -

这篇关于仅在特定条件下用“-"符号替换 NaN,Python-Pandas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆