【问题标题】:Compare missing values in python pandas from another column比较来自另一列的 python pandas 中的缺失值
【发布时间】:2021-04-09 15:19:40
【问题描述】:

我有一个熊猫数据框,它由两列值组成。某些值丢失了,我想创建第三列来标记两列中是否缺少值或是否已填充。我不确定如何执行此操作,因为我是新手,您能提供的任何帮助将不胜感激

#input 
df = {'First': ['','','A','B','B','C'], 
  'Second': ['12', '', '10', '', '', '11']}
df = pd.DataFrame(data = d)

#Possible output of third column
df['Third'] = ['Secondfilled', 'missing', 'bothfilled', 'Firstfilled', 'Firstfilled', bothfilled']

【问题讨论】:

    标签: python pandas compare missing-data


    【解决方案1】:

    没有 ifelse 或自定义函数的单行解决方案。 通过@SeaBean 的建议进行了改进!

    d = {0: 'Missing', 1: 'FirstFilled', 2: 'SecondFilled', 3: 'BothFilled'}
    df['Third'] = (df.ne('')*(1,2)).sum(1).map(d)
    

    输出:

    print(df)
    
      First Second         Third
    0           12  SecondFilled
    1                    Missing
    2     A     10    BothFilled
    3     B          FirstFilled
    4     B          FirstFilled
    5     C     11    BothFilled
    

    【讨论】:

    • 赞成。也可以用.sum(1)替换.apply(sum, axis = 1),进一步简化。
    • 好主意!谢谢
    【解决方案2】:

    您可以将apply() 与查找字典一起使用。

    lookup = {'10': 'Firstfilled', '01': 'Secondfilled', '11': 'bothfilled', '00': 'missing'}
    
    def fill(row):
        key = '00'
    
        if row['First'] != '':
            key = '1' + key[1]
    
        if row['Second'] != '':
            key = key[0] + '1'
    
        return lookup[key]
    
    df['Third'] = df.apply(fill, axis=1)
    
    # print(df)
    
      First Second         Third
    0           12  Secondfilled
    1                    missing
    2     A     10    bothfilled
    3     B          Firstfilled
    4     B          Firstfilled
    5     C     11    bothfilled
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-18
      • 1970-01-01
      • 1970-01-01
      • 2019-02-19
      • 1970-01-01
      • 2022-06-11
      • 2019-08-11
      • 2016-01-25
      相关资源
      最近更新 更多