None if条件下,缺失数据如何处理?
None in if condition, how to handle missing data?
如果缺少 age
的值,我想创建一个值为 1
的变量。相反,Value
列的输出中的所有内容都是 None
。
raw_data1 = {'id': [1,2,3,5],
'age': [0, np.nan, 10, 2]}
df1 = pd.DataFrame(raw_data1, columns = ['id','age'])
def my_test(b):
if b is None:
return 1
df1['Value'] = df1.apply(lambda row: my_test(row['age']), axis=1)
如何实现呢?我知道有几种方法,但我想重点介绍一个函数的使用,(def my_test
等)。
如果我理解正确,你可以使用:
df1['value'] = np.where(df1['age'].isnull(), 1, '')
输出:
id age value
0 1 0.0
1 2 NaN 1
2 3 10.0
3 5 2.0
你可以用 map
来做这个
df1['Value'] = df1['age'].map(lambda x : 1 if np.isnan(x) else np.nan)
如果你想使用你的功能,你可以像这样使用map
def my_test(b):
if np.isnan(b):
return 1
else:
return np.nan
df1['Value'] = df1['age'].map(lambda x : my_test(x))
您可以使用 row.get('age')
而不是 row['age']
。
get()
returns null 如果 age
不在字典中
改为这样做,
>>> df1.value = df1.age.isna().astype(int)
>>> df1
id age value
0 1 0.0 0
1 2 NaN 1
2 3 10.0 0
3 5 2.0 0
如果缺少 age
的值,我想创建一个值为 1
的变量。相反,Value
列的输出中的所有内容都是 None
。
raw_data1 = {'id': [1,2,3,5],
'age': [0, np.nan, 10, 2]}
df1 = pd.DataFrame(raw_data1, columns = ['id','age'])
def my_test(b):
if b is None:
return 1
df1['Value'] = df1.apply(lambda row: my_test(row['age']), axis=1)
如何实现呢?我知道有几种方法,但我想重点介绍一个函数的使用,(def my_test
等)。
如果我理解正确,你可以使用:
df1['value'] = np.where(df1['age'].isnull(), 1, '')
输出:
id age value
0 1 0.0
1 2 NaN 1
2 3 10.0
3 5 2.0
你可以用 map
来做这个
df1['Value'] = df1['age'].map(lambda x : 1 if np.isnan(x) else np.nan)
如果你想使用你的功能,你可以像这样使用map
def my_test(b):
if np.isnan(b):
return 1
else:
return np.nan
df1['Value'] = df1['age'].map(lambda x : my_test(x))
您可以使用 row.get('age')
而不是 row['age']
。
get()
returns null 如果 age
不在字典中
改为这样做,
>>> df1.value = df1.age.isna().astype(int)
>>> df1
id age value
0 1 0.0 0
1 2 NaN 1
2 3 10.0 0
3 5 2.0 0