gpt4 book ai didi

python - np.where 用字符串创建缺失值

转载 作者:太空宇宙 更新时间:2023-11-04 08:32:22 25 4
gpt4 key购买 nike

我正在创建一个新变量,我的目标是在条件不成立时在“my_var”中获取缺失值,而是在“my_var”中创建值“NaN”,如“df. my_var.isnull().any()",返回 False

import pandas as pd
import numpy as np

data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
'age': [42, 52, 36, 24, 73],
'preTestScore': [4, 24, 31, 2, 3],
'postTestScore': [25, 94, 57, 62, 70]}
df = pd.DataFrame(data, columns = ['name', 'age', 'preTestScore', 'postTestScore'])

df['my_var'] = np.where((df['age']>=36) & (df['age']<=42), 'yes',np.where((df['age']>=52) & (df['age']<=73),'no',np.NaN))

df.my_var.isnull().any()

预期的输出是:

data2 = {'my_var': ['yes', 'no', 'yes', np.NaN, 'no']}

df2 = pd.DataFrame(data2, columns = ['my_var'])
df2

最佳答案

您可以使用 numpy.select 而不是嵌套的 numpy.where:

conditions = [df['age'].between(36, 42), df['age'].between(52, 73)]
values = ['yes', 'no']

df['my_var'] = np.select(conditions, values, None)

print(df)

name age preTestScore postTestScore my_var
0 Jason 42 4 25 yes
1 Molly 52 24 94 no
2 Tina 36 31 57 yes
3 Jake 24 2 62 None
4 Amy 73 3 70 no

不清楚您对最终条件的要求:

print(df['my_var'].isnull().any())

True

如果您正在检查 bool 值 True,而不是“Truthy”值,我强烈建议您使用 True/False 而不是 "is"/“否”

关于python - np.where 用字符串创建缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51875755/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com