• pandas数组(pandas Series)-(4)NaN的处理


    上一篇pandas数组(pandas Series)-(3)向量化运算里说到,将两个 pandas Series 进行向量化运算的时候,如果某个 key 索引只在其中一个 Series 里出现,计算的结果会是 NaN ,那么有什么办法能处理 NaN 呢?

    1.  dropna() 方法:

    此方法会把所有为 NaN 结果的值都丢弃,相当于只计算共有的 key 索引对应的值:

    import pandas as pd
    
    s1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
    s2 = pd.Series([10, 20, 30, 40], index=['c', 'd', 'e', 'f'])
    
    s3 = s1+s2
    print(s3)
    
    # 结果:
    a     NaN
    b     NaN
    c    13.0
    d    24.0
    e     NaN
    f     NaN
    dtype: float64
    
    
    print(s3.dropna())
    
    # 结果:
    c    13.0
    d    24.0
    dtype: float64

    2.  fill_value 参数:

    设置 fill_value参数可以给一个Series没有key索引对应值的时候设置一个填充值:

    s1 = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])
    s2 = pd.Series([10, 20, 30, 40], index=['c', 'd', 'e', 'f'])
    s3 = s1.add(s2, fill_value=0)
    print(s3)
    
    # 结果:
    a     1.0
    b     2.0
    c    13.0
    d    24.0
    e    30.0
    f    40.0
    dtype: float64

    这样, s2 里虽然没有 'a','b' 这个索引 key , s1 里虽然没有 'e','f' 这两个 key ,但是在运算的时候,会用 0 去填充进行运算,也可以设置为其他值.

    可见,以上这两种方法的区别就在于,一个会除去两个 Series 不共有的 key ,一个会用填充值去填补不共有的 key 的值.

  • 相关阅读:
    Python
    按行读取文本,去重行
    Python字符串---固定长度分割字符串
    python终端打印带颜色的print
    Django安装与删除
    Python拼接字符串的7种方法
    CSS指定标签样式style选择器
    python 使用函数名的字符串调用函数(4种方法)
    test
    字符串常用操作
  • 原文地址:https://www.cnblogs.com/liulangmao/p/9227116.html
Copyright © 2020-2023  润新知