Python 熊猫:为另一列是否为空创建新列
我正在尝试在日期框中创建新列,该日期框将指示其余列为空或非空。我认为这应该是相当简单的,但我有困难,使代码完全正确Python 熊猫:为另一列是否为空创建新列,python,pandas,Python,Pandas,我正在尝试在日期框中创建新列,该日期框将指示其余列为空或非空。我认为这应该是相当简单的,但我有困难,使代码完全正确 for column, row in df.iterrows(): if(pd.isnull(row[column])): df[column + 'Blank or Not'] = "blank" else: df[column + 'Blank or Not'] = "not blank" 这就是错误: TypeError: unsupported opera
for column, row in df.iterrows():
if(pd.isnull(row[column])):
df[column + 'Blank or Not'] = "blank"
else:
df[column + 'Blank or Not'] = "not blank"
这就是错误:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
IndexError: index out of bounds
当我将其更改为以下内容时:
for column, row in df.iterrows():
if(pd.isnull(row[column])):
df[str(column) + 'Blank or Not'] = "blank"
else:
df[str(column) + 'Blank or Not'] = "not blank"
这就是错误:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
IndexError: index out of bounds
我怀疑列名是int,所以请使用:
if(pd.isnull(row[column])):
df[str(column) + 'Blank or Not'] = "blank"
else:
df[str(column) + 'Blank or Not'] = "not blank"
或者在python 3中,可以使用f字符串:
f"{column}Blank or Not"
编辑:我想你想做一些稍微不同的事情:
In [21]: df
Out[21]:
0 1
0 NaN 1
In [22]: df.isnull().applymap({True: 'Blank', False: 'Not Blank'}.get)
Out[22]:
0 1
0 Blank Not Blank
我怀疑列名是int,所以请使用:
if(pd.isnull(row[column])):
df[str(column) + 'Blank or Not'] = "blank"
else:
df[str(column) + 'Blank or Not'] = "not blank"
或者在python 3中,可以使用f字符串:
f"{column}Blank or Not"
编辑:我想你想做一些稍微不同的事情:
In [21]: df
Out[21]:
0 1
0 NaN 1
In [22]: df.isnull().applymap({True: 'Blank', False: 'Not Blank'}.get)
Out[22]:
0 1
0 Blank Not Blank
你是对每一列都这样做还是只对一列这样做?你能试试我的编辑
df.isnull().applymap({True:'Blank',False:'notblank'}.get)
?你是对每一列这样做还是只对一列这样做?你能试试我的编辑df.isnull().applymap({True:'Blank',False:'notblank'}.get)吗
?@MadelineKinnaird我想你应该为df.columns中的列而不是iterrows执行操作。@MadelineKinnaird我想你应该为df.columns中的列而不是iterrows执行操作。