代码之家  ›  专栏  ›  技术社区  ›  dina

pandas-为丢失的记录填写默认值

  •  0
  • dina  · 技术社区  · 4 年前

    我想通过以下方式填写数据集中缺失的数据:
    我的数据可以包含以下形状之一:

    ['circle', 'square', 'triangle']
    

    每个形状都具有宽度和高度属性,
    我想填充缺失的数据:如果我的数据集缺少其中一个形状,它会用默认值添加它
    (示例的默认值:“height”=10,“width”=5)

    示例:如果这是我的数据集:

    data = [
     {'shape': 'circle', 'height': 5, 'width': 4},
     {'shape': 'circle', 'height': 2, 'width': 3},
     {'shape': 'square', 'height': 6, , 'width': 5}
    ]
    

    缺少:三角形,用默认宽度填充;身高
    结果将是:

    data = [
     {'shape': 'circle', 'height': 5, 'width': 4},
     {'shape': 'circle', 'height': 2, 'width': 3},
     {'shape': 'square', 'height': 6, 'width': 2},
     {'shape': 'triangle', 'height': 10, 'width': 5} # added by code with default values
    ]
    

    我的代码:

    shapes = ['circle', 'square', 'triangle']
    df = pd.DataFrame(data)
    # df.?? some code to fill in missing data
    
    2 回复  |  直到 4 年前
        1
  •  2
  •   Arne    4 年前

    在制作数据帧之前,我会将缺少值的条目添加到数据中,这样它就已经有了正确的行数。然后,您可以通过将带有默认值的字典传递给 df.fillna() :

    import pandas as pd
    
    data = [
     {'shape': 'circle', 'height': 5, 'width': 4},
     {'shape': 'circle', 'height': 2, 'width': 3},
     {'shape': 'square', 'height': 6, 'width': 5}
    ]
    
    shapes = ['circle', 'square', 'triangle']
    
    shapes_present = {d['shape'] for d in data}
    shapes_missing = set(shapes) - shapes_present
    
    for shape in shapes_missing:
        data.append({'shape': shape})
        
    df = pd.DataFrame(data)
    df.fillna({'height': 10, 'width': 5}, inplace=True)
    df
    
        shape       height  width
    0   circle      5.0     4.0
    1   circle      2.0     3.0
    2   square      6.0     5.0
    3   triangle    10.0    5.0
    
        2
  •  1
  •   fsimonjetz    4 年前

    您可以使用默认值制作另一个df,类似于

    defaults = pd.DataFrame({'shape': shapes, 'height': 10, 'width': 5})
    
    # result
          shape  height  width
    0    circle      10      5
    1    square      10      5
    2  triangle      10      5
    

    然后将原始df与 defaults 尚未出现在 df :

    pd.concat([df, defaults[~defaults['shape'].isin(df['shape'])]], 
              ignore_index=True)
    
    # result
          shape  height  width
    0    circle       5      4
    1    circle       2      3
    2    square       6      5
    3  triangle      10      5