去除熊猫 DF 列上的空白将 bool 值变为 NaN

pur*_*oyd 1 python whitespace boolean strip pandas

我有一个 Pandas 数据框,它有一列包含字符串值和布尔值。由于这种差异,列的 dtype 推断为“对象”。当我在此列上运行 .str.strip() 时,它会将所有布尔值转换为 NaN。有谁知道我如何防止这种情况?我会同意布尔值变成字符串,但是南?

jez*_*ael 6

借用 df 从piRSquared

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

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

如果需要混合类型 - 带有字符串的布尔值添加combine_first替换NaNs 到boolean

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

如果需要转换所有列:

df = df.astype(str).applymap(lambda x: x.strip())
Run Code Online (Sandbox Code Playgroud)

或者:

df = df.astype(str).apply(lambda x: x.str.strip())
Run Code Online (Sandbox Code Playgroud)


piR*_*red 5

设置

df = pd.DataFrame(dict(A=[' a', ' b ', True, False, 'True']))
Run Code Online (Sandbox Code Playgroud)

选项 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
Run Code Online (Sandbox Code Playgroud)

注:
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
Run Code Online (Sandbox Code Playgroud)

选项 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
Run Code Online (Sandbox Code Playgroud)

这里也保留了混合类型。


我们可以用来pd.DataFrame.replace操作整个数据框

df.replace('^\s+|\s+$', '', regex=True)

       A
0      a
1      b
2   True
3  False
4   True
Run Code Online (Sandbox Code Playgroud)