【问题标题】:Assign value to column based on lookup table using pandas [duplicate]使用熊猫根据查找表为列分配值[重复]
【发布时间】:2020-10-31 22:43:45
【问题描述】:

我有以下矩阵:

destinations = ["DC","NY","SF","AL"]

workinDays = [[3, 5, 7, 7], 
                [5, 5, 7, 7],
                [7, 7, 7, 7],
                [7, 7, 7, 7]]

working_days_df = pd.DataFrame(data=workinDays, columns=destinations,
                 index=destinations).astype(str) + " working days"

基于上面的矩阵(当你运行上面的代码时,你会得到一个数据集形式的矩阵)我想将值分配给另一个数据集other_df,它最多有 100 行:

dest1   dest2
DC      DC
NY      AL
...

所以我想添加一个新列,从上面的矩阵中读取正确的值。例如,在第 2 行,dest1 是 NY,dest2 是 AL。所以基于矩阵,它的值应该是 7。我该怎么做?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    IIUC,你可以进行查找:

    df_other['new'] = working_days_df.lookup(df_other['dest1'], df_other['dest2'])
    

    这里,working_days_df 是您的矩阵 DataFrame,而 df_other 是您要查找值的那个。

    【讨论】:

    • 这只是转换当前数据集,但不会映射到他提到的其他数据集。可以通过合并来编辑它,就像我的解决方案一样。
    • @AkshaySehgal 刚刚注意到并修复,谢谢。
    • DataFrame.lookup 自 1.2.0 版起已弃用。
    【解决方案2】:

    执行以下操作 -

    df1 = df.unstack().reset_index()
    df1.columns = ['dest1', 'dest2', 'workingdays']
    
    #the second dataframe that you mention is the other_df
    pd.merge(other_df,df1,how='left',on = ['dest1', 'dest2'])
    
    dest1   dest2   workingdays
    0   DC  DC  3 working days
    1   DC  NY  5 working days
    2   DC  SF  7 working days
    3   DC  AL  7 working days
    4   NY  DC  5 working days
    5   NY  NY  5 working days
    6   NY  SF  7 working days
    7   NY  AL  7 working days
    8   SF  DC  7 working days
    9   SF  NY  7 working days
    10  SF  SF  7 working days
    11  SF  AL  7 working days
    12  AL  DC  7 working days
    13  AL  NY  7 working days
    14  AL  SF  7 working days
    15  AL  AL  7 working days
    

    【讨论】:

      猜你喜欢
      • 2019-09-30
      • 2020-12-11
      • 2021-06-05
      • 2019-12-28
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      • 2019-01-23
      相关资源
      最近更新 更多