【问题标题】:Dealing with missing data in Pandas and Numpy处理 Pandas 和 Numpy 中的缺失数据
【发布时间】:2015-12-10 13:04:00
【问题描述】:

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

  • a) 在 C 列中,替换 np.NaN with 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

【问题讨论】:

    标签: python-2.7 numpy pandas missing-data


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      • 2014-10-19
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-05
      相关资源
      最近更新 更多