【问题标题】:how to replace list of columns with condition on one col by dict\df如何用dict \ df在一列上用条件替换列列表
【发布时间】:2020-12-07 09:39:09
【问题描述】:

我喜欢在一个列上按条件更改列列表中的值,使用 dict\df 我得到了 df\dict

类似的东西

list_of_cols=["col1",.."col5"]
df[list_of_cols]=where[df["A"]==dict],dict

这是数据

data={"col1":[np.nan,3,4,5,9,2,6],
"col2":[4,2,4,6,0,1,5],
"col3":[7,6,0,11,3,6,7],
"col4":[14,11,22,8,6,np.nan,9],
"col5":[0,5,7,3,8,2,9],
"type":["A","A","C","A","B","A","E"],
"number":["one","two","two","one","one","two","two"]}
df=pd.DataFrame.from_dict(data)
df

这是我想将 df["type"] 与 dict 映射的 dict\df 所以 type==A , col1-col5 将是 0

my_dict={"A":0,"B":21,"C":14,"D":9}
my_dict=pd.DataFrame.from_dict(my_dict, orient='index')
my_dict

这就是我想要得到的

data={"col1":[0,0,14,0,21,0,6],
      "col2":[0,0,14,0,21,0,5],
      "col3":[0,0,14,0,21,0,7],
      "col4":[0,0,14,0,21,0,0.9],
      "col5":[0,0,14,0,21,0,9],
      "type":["A","A","C","A","B","A","E"],
"number":["one","two","two","one","one","two","two"]}
df=pd.DataFrame.from_dict(data)
df

【问题讨论】:

    标签: python pandas dictionary replace mapping


    【解决方案1】:

    IIUC,使用isin过滤掉类型,然后使用applymap直接赋值:

    m = df["type"].isin(my_dict)
    
    df.loc[m, "col1":"col5"] = df.loc[m, "col1":"col5"].apply(lambda d: pd.Series.map(df["type"], my_dict))
    
    print (df)
    
       col1  col2  col3  col4  col5 type number
    0   0.0   0.0   0.0   0.0   0.0    A    one
    1   0.0   0.0   0.0   0.0   0.0    A    two
    2  14.0  14.0  14.0  14.0  14.0    C    two
    3   0.0   0.0   0.0   0.0   0.0    A    one
    4  21.0  21.0  21.0  21.0  21.0    B    one
    5   0.0   0.0   0.0   0.0   0.0    A    two
    6   6.0   5.0   7.0   9.0   9.0    E    two
    

    【讨论】:

    • 它的工作,但如果我的字典是 {"A":{"col1":0,"col2":1,"col3":2,"col4":1,"col5":2 }} 你会怎么做呢?
    • 使用pd.DataFrame({"A":{"col1":0,"col2":1,"col3":2,"col4":1,"col5":2}}).T.combine_first(df.set_index("type"))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 2021-08-17
    相关资源
    最近更新 更多