Python 如果所有行都为空,如何添加新的布尔列?
我有一个数据帧:Python 如果所有行都为空,如何添加新的布尔列?,python,pandas,Python,Pandas,我有一个数据帧: Out[8]: 0 1 2 0 0 1.0 2.0 1 NaN NaN NaN 2 0 0.0 NaN 3 0 1.0 2.0 4 0 1.0 2.0 我想添加一个新的布尔列“abc”,如果该行包含所有NaN,“abc”为“true”,否则“abc”为“false”,例如: 0 1 2 abc 0 0 1.0 2.0 false 1 NaN NaN NaN
Out[8]:
0 1 2
0 0 1.0 2.0
1 NaN NaN NaN
2 0 0.0 NaN
3 0 1.0 2.0
4 0 1.0 2.0
我想添加一个新的布尔列“abc”,如果该行包含所有NaN,“abc”为“true”,否则“abc”为“false”,例如:
0 1 2 abc
0 0 1.0 2.0 false
1 NaN NaN NaN true
2 0 0.0 NaN false
3 0 1.0 2.0 false
4 0 1.0 2.0 false
这是我检查行的代码
def check_null(df):
return df.isnull().all(axis=1)
它返回我想要的部分内容:
check_null(df)
Out[10]:
0 false
1 true
2 false
3 false
4 false
dtype: bool
所以,我的问题是,我如何才能在其中添加“abc”作为一个新列?
我试过了
它表明:
ValueError:(“没有对象类型命名为1的轴,'在索引0'处出现”)
使用
isna
和all
df.isna().all(axis = 1)
Out[121]:
0 False
1 True
2 False
3 False
4 False
dtype: bool
你不需要应用它
def check_null(df):
return df.isnull().all(axis=1)
check_null(df)
Out[123]:
0 False
1 True
2 False
3 False
4 False
dtype: bool
如果您确实想要应用
它,您需要更改您的功能,删除轴=1
def check_null(df):
return df.isnull().all()
df.apply(check_null,1)
Out[133]:
0 False
1 True
2 False
3 False
4 False
dtype: bool
不要使用apply,直接赋值:
df['abc']=df.isnull().all(axis='columns')
df['abc']=check_null(df)
因为你的函数是一个线性函数,你可以这样做:df['abc']=df.isnull().all(axis=1)
。这个代码已经在问题中,我认为问题更多的是关于应用itts。还有一个问题:如果我只检查最后两列的NaN值会怎么样?@potentialwjy df.iloc[:,-2:]。apply(check_null,1)谢谢。我只是用类似的方式来理解。无论如何谢谢你
def check_null(df):
return df.isnull().all()
df.apply(check_null,1)
Out[133]:
0 False
1 True
2 False
3 False
4 False
dtype: bool