在pandas-DF列上去掉空白将布尔值转换为NaN



我有一个pandas数据帧,它有一列包含字符串值和布尔值。由于这种差异,列的dtype推断为"object"。当我在这列上运行.str.strip((时,它会将我的所有布尔值转换为NaN。有人知道我该如何防止这种情况发生吗?我可以接受布尔值变成字符串,但是楠?

piRSquared:借用df

首先将所有值转换为string,然后剥离:

df['A'] = df['A'].astype(str).str.strip()
print (df)
A
0      a
1      b
2   True
3  False
4   True

如果需要混合类型-带字符串的布尔型,则添加combine_first以将NaN替换为boolean:

df['A'] = df['A'].str.strip().combine_first(df.A)
print (df)
A
0      a
1      b
2   True
3  False
4   True

如果需要转换所有列:

df = df.astype(str).applymap(lambda x: x.strip())

或者:

df = df.astype(str).apply(lambda x: x.str.strip())

设置

df = pd.DataFrame(dict(A=[' a', ' b ', True, False, 'True']))

选项1
pd.Series.str.strip字符串访问器方法与fillna一起使用

df.A.str.strip().fillna(df.A)
0        a
1        b
2     True
3    False
4     True
Name: A, dtype: object

注意:
typestrbool

df.A.str.strip().fillna(df.A).apply(type)
0     <class 'str'>
1     <class 'str'>
2    <class 'bool'>
3    <class 'bool'>
4     <class 'str'>
Name: A, dtype: object

选项2
使用pd.Series.replace

df.A.replace('^s+|s+$', '', regex=True)
0        a
1        b
2     True
3    False
4     True
Name: A, dtype: object

混合类型也保留在这里。


我们可以使用pd.DataFrame.replace对整个数据帧进行操作

df.replace('^s+|s+$', '', regex=True)
A
0      a
1      b
2   True
3  False
4   True

最新更新