python-2.7 - 处理 Pandas 和 Numpy 中的缺失数据

标签 python-2.7 numpy pandas missing-data

我有以下数据样本。我愿意

  • a) 在 C 列中,np.NaN 替换为 999
  • b) 在 D 列中,将 '' 替换为 np.NaN

我的两次尝试都不起作用,我不知道为什么。

import pandas
from pandas import DataFrame
import numpy as np


df = DataFrame({'A' : ['foo', 'foo', 'foo', 'foo',
                        'bar', 'bar', 'bar', 'bar'],
                 'B' : ['one', 'one', 'two', 'three',
                        'two', 'two', 'one', 'three'],
                 'C' : [1, np.NaN, 1, 2, np.NaN, 1, 1, 2], 'D' : [2, '', 1, 1, '', 2, 2, 1]})

print df

df.C.fillna(999)
df.D.replace('', np.NaN)

print df

Output: 

 A      B   C  D
0  foo    one   1  2
1  foo    one NaN   
2  foo    two   1  1
3  foo  three   2  1
4  bar    two NaN   
5  bar    two   1  2
6  bar    one   1  2
7  bar  three   2  1
     A      B   C  D
0  foo    one   1  2
1  foo    one NaN   
2  foo    two   1  1
3  foo  three   2  1
4  bar    two NaN   
5  bar    two   1  2
6  bar    one   1  2
7  bar  three   2  1

最佳答案

这些操作返回数据的副本(大多数 pandas 操作的行为相同),除非您明确说明,否则它们不会就地操作(默认为 inplace=False),请参阅fillnareplace :

df.C.fillna(999, inplace=True)
df.D.replace('', np.NaN, inplace=True)

或分配回:

df['C'] = df.C.fillna(999)
df['D'] = df.D.replace('', np.NaN)

此外,我强烈建议您使用下标运算符 [] 访问列,而不是使用点运算符 . 作为属性,以避免出现歧义行为

In [60]:
df = pd.DataFrame({'A' : ['foo', 'foo', 'foo', 'foo',
                        'bar', 'bar', 'bar', 'bar'],
                 'B' : ['one', 'one', 'two', 'three',
                        'two', 'two', 'one', 'three'],
                 'C' : [1, np.NaN, 1, 2, np.NaN, 1, 1, 2], 'D' : [2, '', 1, 1, '', 2, 2, 1]})
​
df.C.fillna(999, inplace =True)
df.D.replace('', np.NaN, inplace=True)
df

Out[60]:
     A      B    C   D
0  foo    one    1   2
1  foo    one  999 NaN
2  foo    two    1   1
3  foo  three    2   1
4  bar    two  999 NaN
5  bar    two    1   2
6  bar    one    1   2
7  bar  three    2   1

关于python-2.7 - 处理 Pandas 和 Numpy 中的缺失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32566320/

相关文章:

python - Matplotlib:在 3D 条形图中格式化 x 轴上的日期

python - 需要找到黑点

python - 检查 2d 数组是否存在于 Python 中的 3d 数组中?

基于公共(public)键合并 2 个字典列表的 Pythonic 方法

regex - 找到 5 个相同的字符后修剪字符串

python - 在 python 2.7 中使用 smtp 时出现 keyerror

python - 使用 Python 读取 csv 文件第 i 列的最佳方法是什么?

python - 如何在Python中实现itk图片和SimpleITK图片的转换?

python - 如何在 Pandas 中添加排序功能?

Python Pandas .where 具有超过 2 个可能的条件输入