pandas 数据框用NaN替换空白 [英] pandas dataframe replace blanks with NaN
本文介绍了 pandas 数据框用NaN替换空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个带有空单元格的数据框,想用NaN替换这些空单元格. 先前在该论坛上提出的解决方案是可行的,但前提是该单元格包含空格:
I have a dataframe with empty cells and would like to replace these empty cells with NaN. A solution previously proposed at this forum works, but only if the cell contains a space:
df.replace(r'\s+',np.nan,regex=True)
当单元格为空时,此代码不起作用.有没有人建议用熊猫码代替空细胞.
This code does not work when the cell is empty. Has anyone a suggestion for a panda code to replace empty cells.
Wannes
推荐答案
我认为最简单的方法是进行两次替换:
I think the easiest thing here is to do the replace twice:
In [117]:
df = pd.DataFrame({'a':['',' ','asasd']})
df
Out[117]:
a
0
1
2 asasd
In [118]:
df.replace(r'\s+',np.nan,regex=True).replace('',np.nan)
Out[118]:
a
0 NaN
1 NaN
2 asasd
这篇关于 pandas 数据框用NaN替换空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文