代码之家  ›  专栏  ›  技术社区  ›  Claudiu Creanga

在pd.dataframe.query()后面插入值并保留原始数据

  •  2
  • Claudiu Creanga  · 技术社区  · 7 年前

    我有一个DF:

    df = pd.DataFrame([[1,1],[3,4],[3,4]], columns=["a", 'b'])
        a   b
    0   1   1
    1   3   4
    2   3   4
    

    我必须根据查询筛选这个df。查询可能很复杂,但这里我使用的是一个简单的查询:

    items = [3,4]
    df.query("a in @items and b == 4")
        a   b
    1   3   4
    2   3   4
    

    仅对这些行,我想在新列中添加一些值:

    configuration = {'c': 'action', "d": "non-action"}
    for k, v in configuration.items():
        df[k] = v
    

    其余行应具有空值或np.nan。所以我的最终df应该是:

        a   b   c       d
    0   1   1   np.nan  np.nan
    1   3   4   action  non-action
    2   3   4   action  non-action
    

    问题是为了进行查询,我最终得到了一个数据帧的副本。然后我必须以某种方式合并它们并用索引替换修改过的行。如何在不将原始df中的行按索引替换为查询的行的情况下执行此操作?

    1 回复  |  直到 7 年前
        1
  •  3
  •   BENY    7 年前

    使用 combine_first 具有 assign

    df.query("a in @items and b == 4").assign(**configuration).combine_first(df)
    Out[138]: 
         a    b       c           d
    0  1.0  1.0     NaN         NaN
    1  3.0  4.0  action  non-action
    2  3.0  4.0  action  non-action