K.M*_*.M. 4 python null pandas
I'm trying to create a column in my data set such that any null values can be set to 0, and non-null values are set to 1. For starters, my column of data called '9Age', roughly speaking, looks like this:
NaN
6
5
NaN
2
NaN
3
5
4
Run Code Online (Sandbox Code Playgroud)
Setting null values to 0 can be as easy as doing this:
Age0 = df['9Age'].fillna(0)
Run Code Online (Sandbox Code Playgroud)
However, here's the rest of my attempt: Deciding whether a value is null or not was done below:
Age1 = df['9Age'].notnull()
Run Code Online (Sandbox Code Playgroud)
This changes '9Age' to:
False
True
True
False
True
False
True
True
True
Run Code Online (Sandbox Code Playgroud)
That is, it returns True if the observation is not null, but False if it is. Following this logic, the next step I took was writing this:
AgeExist = Age1.map({'False':0, 'True': 1})
Run Code Online (Sandbox Code Playgroud)
However, to my dismay, AgeExist yields
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
NaN
Run Code Online (Sandbox Code Playgroud)
或者,一堆空值。我哪里出错了,有什么更好的方法来解决所有这些问题?
除非我大错特错,否则很简单Trueis not 'True'。
AgeExist = Age1.map({False:0, True: 1})
Run Code Online (Sandbox Code Playgroud)
应该为你工作。
您可以使用以下方法将一系列 True/False 值转换为其整数表示形式.astype
import pandas as pd
import numpy as np
df = pd.DataFrame()
df['col'] = [np.NaN, 6, 5, np.NaN]
col = df['col'].notnull()
col.astype(int)
Run Code Online (Sandbox Code Playgroud)