python - pandas 将字符串列转换为 boolean 值

标签 python pandas dataframe boolean

我正在尝试将包含 True/False 和 null 值的字符串格式的列转换为 boolean 值。但无论我做什么,我最终都会得到所有 True 值或 False 下面是我的方法

考虑以下数据帧

df = pd.DataFrame({'w':['True', np.nan, 'False'
                        'True', np.nan, 'False']})
df['w'].dtypes
Out: dtype('O')

df['w'].unique()
Out: array([True, nan, False], dtype=object)

d = {'nan': np.nan,'False':False, 'True': True}
df['w']=df['w'].map(d)

df['w'].dtypes
Out: dtype('O')

df['w'].unique()
array([nan], dtype=object)

我使用的另一种方法是 this所以帖子:

d = {'nan': 0,'False':0, 'True': 1 }
df['w']=df['w'].map(d)
df['w']=df['w'].astype('bool')

现在它变成 bool 但将所有值转换为 True

df['w'].dtypes
Out: dtype('bool')

df['w'].unique()
Out: array([ True])

我做错了什么? 我希望所有空值都为空

最佳答案

我认为没有必要,因为您的原始数据包含带有 nan 的 boolean 值,dtypes 是 object 因为混合值 - 带有缺失值的 boolean 值:

df = pd.DataFrame({'w':['True', np.nan, 'False']})

print (df['w'].unique())
['True' nan 'False']

print ([type(x) for x in df['w'].unique()])
[<class 'str'>, <class 'float'>, <class 'str'>]

如果 nan 也是字符串,那么您的解决方案有效:

df = pd.DataFrame({'w':['True', 'nan', 'False']})

print ([type(x) for x in df['w'].unique()])
[<class 'str'>, <class 'str'>, <class 'str'>]

d = {'nan': np.nan,'False':False, 'True': True}
df['w'] = df['w'].map(d)

print (df['w'].unique())
[True nan False]

print ([type(x) for x in df['w'].unique()])
[<class 'bool'>, <class 'float'>, <class 'bool'>]

df = pd.DataFrame({'w':[True, np.nan, False]})

print (df['w'].unique())
[True nan False]

print ([type(x) for x in df['w'].unique()])
[<class 'bool'>, <class 'float'>, <class 'bool'>]

如果想要将 nan 替换为 False,请使用 Series.fillna :

df['w'] = df['w'].fillna(False)
print (df)
       w
0   True
1  False
2  False

print (df['w'].dtypes)
bool

print (df['w'].unique())
[ True False]

关于python - pandas 将字符串列转换为 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59064373/

相关文章:

python - python中与append()函数相反的是什么?

python - Pandas 根据天数创建时间序列

python - 将字典拆分为现有列

python - 按所有选项划分两个不同大小的数据框

python - 将 'boxes' 与 imgflip 的 API 一起使用时出现错误消息

python - 带有python插件的snapcraft : returned non-zero exit status 2

python - 将 lambda 与命名函数应用于 pandas DataFrame 之间的性能差异

python - 根据其他列的值作为一组设置列中的值

python - 根据其他列值从 DataFrame 获取值 (PySpark)

Python 身份验证 API