【问题标题】:Updating column value based on multiple conditions across multiple dataframes根据多个数据帧中的多个条件更新列值
【发布时间】:2019-05-28 23:28:41
【问题描述】:

我有两个数据框,我正在尝试根据工具和位置两个条件更新 DF1 中的名称-

数据框 -

第一个

DF1

NAME    Tool    Location
-       tool_1  location_1
-       tool_15 location_2 
-       tool_19 location_3 

第二个 -

DF2

NAME    Tool    Location
name51  tool_1  location_1
name42  tool_15 location_2 
name33  tool_19 location_3

我已经尝试使用 numpy where 条件检查两个值,但是收到错误提示 -

ValueError: 只能比较标签相同的 Series 对象

我了解问题是我的两个数据框中的行号不同。我尝试了一些重置索引的解决方案,但没有成功。

这是我尝试的查询 -

DF1['NAME'] = np.where((DF1.Tool == DF2.Tool) & (DF1.Location== DF2.Location), DF2.Name)

有什么办法可以解决这个问题?我无法将两个数据框都与行的确切长度相匹配。

DF1 的预期结果是 -

DF1

NAME    Tool    Location
name51  tool_1  location_1
name42  tool_15 location_2 
name33  tool_19 location_3

谢谢,

【问题讨论】:

    标签: python pandas numpy dataframe


    【解决方案1】:

    合并和reindex():

    DF1=DF1.merge(DF2,on=['Tool','Location'],suffixes=('_x','')).reindex(DF1.columns,axis=1)
    

         NAME     Tool    Location
    0  name51   tool_1  location_1
    1  name42  tool_15  location_2
    2  name33  tool_19  location_3
    

    【讨论】:

    • 非常感谢您的意见!如果假设我的查询看起来像这样 - DF1['NAME'] = np.where((DF1.Tool == DF2.Tool) & (DF1.Location.isin(DF2.Location)), DF2.Name),您将如何解决。我有更多需要匹配的字符串列,但它们并不总是完全相同,只有前 2 个字符匹配
    • @PaulGirtavic 问题是这看起来索引明智,假设 tool15 超过 tool_1,这将给出错误,所以在这里合并是更好的选择
    • @PaulGirtavic 你也可以试试df1['NAME']=np.where(df1.Tool.eq(df2.Tool)&(df1.Location.isin(df2.Location)),df1.Tool.map(df2.set_index('Tool')['NAME']),df1.NAME) 但我还是更喜欢这里的合并解决方案
    猜你喜欢
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2021-03-02
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    相关资源
    最近更新 更多