【问题标题】:update\replace df [cols] by df [cols]用 df [列] 更新\替换 df [列]
【发布时间】:2020-10-08 11:55:07
【问题描述】:

我有两个具有相同索引的 df,并且我喜欢仅在 name=="A" 时更新\替换列列表。

所以我得到 name=="A" 我希望它替换 列数 ->cols=[col1,col2,col3,col4]

所以我有这个 df

first_data={"col1":[2,3,4,5,7],
"col2":[4,2,4,6,4],
"col3":[7,6,9,11,2],
"col4":[14,11,22,8,5],
"name":["A","A","V","A","B"],
"n_roll":[8,2,1,3,9]}
df1=pd.DataFrame.from_dict(first_data)
df1

和秒 df

sec_df={"col1":[55,0,57,1,3],
"col2":[55,0,4,4,53],
"col3":[55,33,9,0,2],
"col4":[55,0,22,4,5],
"name":["A","A","V","A","B"],
"hight":[8,2,1,3,9]}
df2=pd.DataFrame.from_dict(sec_df)
df2

我喜欢这样做 df1.loc[df1["name"]=="A"][cols]=df2.loc[df2["name"]=="A"][cols]

所以我想得到这个

data={"col1":[55,0,4,1,7],
"col2":[55,0,4,4,4],
"col3":[55,33,9,0,2],
"col4":[55,0,22,4,5],
"name":["A","A","V","A","B"],
"n_roll":[8,2,1,3,9]}
df=pd.DataFrame.from_dict(data)
df

【问题讨论】:

    标签: python pandas replace updates


    【解决方案1】:

    IIUC 你可以update:

    df1 = df1.set_index("name", append=True)
    
    df1.update(df2[df2["name"].eq("A")].set_index("name", append=True).filter(like="col"))
    

    如果您不需要关心列name,而只需要根据索引进行更新,您可以这样做:

    df1.update(df2[df2["name"].eq("A")].filter(like="col"))
    
      name  col1  col2  col3  col4  n_roll
    0    A  55.0  55.0  55.0  55.0       8
    1    A   0.0   0.0  33.0   0.0       2
    2    V   4.0   4.0   9.0  22.0       1
    3    A   1.0   4.0   0.0   4.0       3
    4    B   7.0   4.0   2.0   5.0       9
    

    【讨论】:

    • 我必须使用列列表,因为在实际数据中,名称不同,并且无法按“COL”一词进行过滤,可能类似于:df1.update(df2[df2[" name"].eq("A")].set_index("name", append=True)[cols] 当 cols=["col1","col2",col3,"col4"]
    猜你喜欢
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    • 2018-07-19
    • 2021-07-09
    • 2020-10-28
    相关资源
    最近更新 更多