python - 用空值替换数据框子集的空格

标签 python pandas

对于下面的数据框,

 id  words   A   B   C   D  E  
 1   new a   1       1   
 2   good v  1  
 3   star c          1
 4   never                  
 5   final   

我尝试使用以下代码将空格替换为空值:

df1.loc[:, ["A", "B", "C", "E", "D" ]].replace (r'\s+', np.nan, regex = True, inplace = True)

但是没有用。我也试过这段代码:

df1[["A", "B", "C", "E", "D" ]].replace (r'\s+', np.nan, regex = True, inplace = True)

它也没有用。

但是使用下面的代码,它起作用了:

df1.A.replace (r'\s+', np.nan, regex = True, inplace = True)
df1.B.replace (r'\s+', np.nan, regex = True, inplace = True)
df1.C.replace (r'\s+', np.nan, regex = True, inplace = True)
df1.D.replace (r'\s+', np.nan, regex = True, inplace = True)
df1.E.replace (r'\s+', np.nan, regex = True, inplace = True)

有人知道为什么吗?谢谢。

最佳答案

当您从 DataFrame 中选择列时,返回的对象是一个副本。如果您对该副本调用方法,则 inplace 参数将对副本起作用——而不是对实际的 DataFrame。

df1.loc[:, ["A", "B", "C", "E", "D" ]].replace (r'\s+', np.nan, regex = True, inplace = True)

这一行实际上修改了一个 DataFrame,但是由于该 DataFrame 没有分配给任何东西,所以您看不到结果。

使用示例 DataFrame:

df = pd.DataFrame()
df['words'] = ['x', 'y', 'z', 't']
df['A'] = [1, 1, '', '']
df['B'] = ['', '', '', '']
df['C'] = [1, '', 1, '']
df['D'] = ['', '   ', '     ', ' ']
df['E'] = ['    ', ' ', '', '']

df
Out: 
  words  A B  C      D     E
0     x  1    1             
1     y  1                  
2     z       1             
3     t                     

您需要将结果分配回来:

cols = ["A", "B", "C", "E", "D" ]   
df.loc[:, cols] = df.loc[:, cols].replace (r'\s+', np.nan, regex=True)

请注意,这将仅替换具有 1 个或多个空格的单元格。如果您也需要替换空字符串,请将其更改为

df.loc[:, cols] = df.loc[:, cols].replace (r'\s*', np.nan, regex=True)

df
Out: 
  words    A    B    C    D    E
0     x    1  NaN    1  NaN  NaN
1     y    1  NaN  NaN  NaN  NaN
2     z  NaN  NaN    1  NaN  NaN
3     t  NaN  NaN  NaN  NaN  NaN

关于python - 用空值替换数据框子集的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44618723/

相关文章:

Python/Django : synonym for field "type" in database model (reserved built-in symbol)

python - 使用树状数据进行 pytest 嵌套参数化

python - 了解 Pandas 的滚动相关性

python - Pandas 时间序列多切片

Python Pandas Bokeh Index错误: list index out of range - why?

python - 如何获取壁橱匹配列表中元素的索引

python - 如何在 DataFrame 中创建显示最后记录峰值的列?

python - 如何在不生成SettingWithCopyWarning的情况下将列插入到DataFrame中

python - Fill_Between 返回 ValueError : Argument dimensions are incompatible

python - 如何在 SQLAlchemy 中的主节点上两次加入详细信息?