我正在尝试将包含 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/