python - 用零填充行其他列有一些值,否则其他列没有值在python pandas中用NaN填充
问题描述
我有如下数据框
import pandas as pd
import numpy as np
k={'ID':[1,2,3,4,5,6],'m1':[20,'',30,40,50,60],
'm2':['',40,40,90,'',''],
'm3':['','','','','',''],
'm4':['','','','','',''],
'm5':['','','','',1,''],
'm6':[10,'','',90,'','']}
df=pd.DataFrame(data=k)
我们检查了同一行的其他行中是否有任何退出值,然后我们需要用零填充它,或者其他确实包含我们必须填充的任何值,NAN
我的结果显示如下
ID m1 m2 m3 m4 m5 m6
1 20 0.0 0.0 0.0 0.0 10.0 # first row and last row has value some vale so we have fill it Zero others rows
2 0 40.0 NaN NaN NaN NaN # there are no value after the second row we have will it with NAN
3 30 40.0 NaN NaN NaN NaN # there are no value after the second row we have will it with NAN
4 40 90.0 0.0 0.0 0.0 90.0 # first row,second row and last row has some value so we have fill it Zero to other rows
5 50 0.0 0.0 0.0 1.0 NaN # first row,and fifth row has some value so we have fill it Zero to other rows and last row with Nan
6 60 NaN NaN NaN NaN NaN # there are no value after the first row we have will it with NAN
解决方案
让我们bfill
尝试mask
s=df.iloc[:,1:]
df.iloc[:,1:]=s.mask(s.mask(s=='').bfill(1).notna()&(s==''),0)
df
ID m1 m2 m3 m4 m5 m6
0 1 20 0 0 0 0 10
1 2 0 40
2 3 30 40
3 4 40 90 0 0 0 90
4 5 50 0 0 0 1
5 6 60
推荐阅读
- azure - 使用 Azure Cli 删除 Azure 文件共享中的旧文件
- python - 熊猫每周时间表,包括假期
- node.js - 我需要在 NPM package.json 和主 index.html 中添加 Babel 和 React 还是只在一个地方就足够了?
- php - 使用 Str::random (或原生 php 方法)的两个标记重合的情况
- reactjs - 如何在 React Native 中实现类似 Android 片段的功能
- c# - 打开包含同名文件的 Zip 文件
- ionic-framework - 使用 Ionic 的移动辅助功能不起作用
- python - 为什么我不能在 VSCode 中查看 Python 某些模块的定义?
- azure-data-factory - 如何获取映射数据流内部的映射数据流名称?
- python - 如何在 Python 中将 Azure Blob 存储中的 CSV 作为流处理