我添加了一个模拟数据框来举例说明我的问题。
我有一个大的数据框,其中某些列缺少值。我想创建一些额外的布尔列,其中1对应于该行中的不丢失值,0对应于缺失值。
names = ['Banana, Andrew Something (Maria Banana)', np.nan, 'Willis, Mr. Bruce (Demi Moore)', 'Crews, Master Terry', np.nan]
room = [100, 330, 212, 111, 222]
hotel_loon = {'Name' : pd.Series(names), 'Room' : pd.Series(room)}
hotel_loon_df = pd.DataFrame(hotel_loon)
在另一个我在stack overflow上发现的问题中,它们非常透彻,而且清楚如何继续跟踪所有缺少值但不是特定值的列。我尝试了该代码的一些变体(即使用where),但是创建所需的东西并没有成功,就像这样:
Name Room Name_present Room_present
0 Banana, Andrew Something (Maria Banana) 100 1 1
1 NaN 330 0 1
2 Willis, Mr. Bruce (Demi Moore) 212 1 1
3 Crews, Master Terry 111 1 1
4 NaN 222 0 1
谢谢您的时间,我相信最终这将是微不足道的,但是由于某些原因,我被卡住了。
您可以将.isnull()
用于您的案件,并将类型从bool
更改为int
:
hotel_loon_df['Name_present'] = (~hotel_loon_df['Name'].isnull()).astype(int)
hotel_loon_df['Room_present'] = (~hotel_loon_df['Room'].isnull()).astype(int)
Out[1]:
Name Room Name_present Room_present
0 Banana, Andrew Something (Maria Banana) 100 1 1
1 NaN 330 0 1
2 Willis, Mr. Bruce (Demi Moore) 212 1 1
3 Crews, Master Terry 111 1 1
4 NaN 222 0 1
~
表示相反的意思,或者不是。
要保存一些键入内容,请使用DataFrame.notnull
,添加一些后缀,然后将结果重新加入。
pd.concat([df, df.notnull().astype(int).add_suffix('_present')], axis=1)
Name Room Name_present Room_present
0 Banana, Andrew Something (Maria Banana) 100 1 1
1 NaN 330 0 1
2 Willis, Mr. Bruce (Demi Moore) 212 1 1
3 Crews, Master Terry 111 1 1
4 NaN 222 0 1
如果仅跟踪Nan字段,则可以使用isnull()函数。
df['name_present'] =df['name'].isnull()
df['name_present'].replace(True,0, inplace=True)
df['name_present'].replace(False,1, inplace=True)
df['room_present'] =df['room'].isnull()
df['room_present'].replace(True,0, inplace=True)
df['room_present'].replace(False,1, inplace=True)