【问题标题】:Pandas creating a conditional column based on the value of another columnPandas 根据另一列的值创建条件列
【发布时间】:2018-09-20 11:07:45
【问题描述】:

我有两个 df 的

df1:

索引文本 1 串1 2串2 3串3 4个 5串5 6个

df2:

索引文本 4串4 6串6

如何根据索引将 df1 中的文本“a”替换为 df2 中的值,使其显示如下。

df3:

索引文本 1 串1 2串2 3串3 4串4 5串5 6串6

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以将 pandas update 用作:

    df1.set_index('index',inplace=True)
    df2.set_index('index',inplace=True)
    df1.update(df2) #df1 is changed
    

    或者

    df1.loc[df2.index,'text'] = df2['text'] #df1 is changed
    

    或者输出到df3然后

    df3 = df1.copy()
    df3.update(df2) #df3 is changed
    

    它们都产生:

           text
    index   
    1   string1
    2   string2
    3   string3
    4   string4
    5   string5
    6   string6
    

    【讨论】:

    • 请更新您的答案,它应该是df1.set_index('index', drop=True, inplace=True)df2.set_index('index', drop=True, inplace=True) 以显示所需的输出。
    • @Nand 签入 pandas 0.23.4 drop=True 不需要。
    • 太棒了!这正是我所需要的,必须做一个简单的列名更改才能在我的情况下工作
    【解决方案2】:

    这会起作用

    pd.merge(df1[[]], df2, left_index=True, right_index=True)
    

    df2.loc[df1.index] 
    

    【讨论】:

    • merge 和 loc 添加的列比我需要的多,谢谢,但 update() 为我解决了问题
    猜你喜欢
    • 2021-03-02
    • 2020-04-16
    • 2022-01-07
    • 2023-01-04
    • 1970-01-01
    • 1970-01-01
    • 2022-10-15
    • 1970-01-01
    • 2020-08-20
    相关资源
    最近更新 更多