代码之家  ›  专栏  ›  技术社区  ›  Ramón J Romero y Vigil

将pandas.dataframe列分配给具有默认值的序列

  •  2
  • Ramón J Romero y Vigil  · 技术社区  · 6 年前

    假设我有一个 DataFrame

    df = pandas.DataFrame({'a': [1,2], 'b': [3,4]}, ['foo', 'bar'])
    
         a  b
    foo  1  3
    bar  2  4
    

    我想添加一个基于另一个的列 Series :

    s = pandas.Series({'foo': 10, 'baz': 20})
    
    foo    10
    baz    20
    dtype: int64
    

    如果数据帧索引值不在序列索引中,如何将序列分配给数据帧的列并提供默认值?

    我在找这种形式的东西:

    df['c'] = s.withDefault(42)
    

    这将导致以下数据帧:

         a b c 
    foo  1 3 10
    bar  2 4 42
    
    #Note: bar got value 42 because it's not in s
    

    提前感谢您的考虑和回应。

    2 回复  |  直到 6 年前
        1
  •  4
  •   piRSquared    6 年前

    使用 map 具有 get

    得到 有一个可用于指定默认值的参数。

    df.assign(c=df.index.map(lambda x: s.get(x, 42)))
    
         a  b   c
    foo  1  3  10
    bar  2  4  42
    

    使用 reindex 具有 fill_value

    df.assign(c=s.reindex(df.index, fill_value=42))
    
         a  b   c
    foo  1  3  10
    bar  2  4  42
    
        2
  •  2
  •   harvpan    6 年前

    你需要使用 join 之间 df 和数据帧,从 s 然后填充 NaN 在您的情况下,默认值是42。

    df['c'] = df.join(pandas.DataFrame(s, columns=['c']))['c'].fillna(42).astype(int)
    

    输出:

        a   b   c
    foo 1   3   10
    bar 2   4   42