【问题标题】:How to set values in a Pandas DataFrame Column equal to values based on another DataFrame如何将 Pandas DataFrame 列中的值设置为等于基于另一个 DataFrame 的值
【发布时间】:2021-03-25 08:48:03
【问题描述】:

我有两个 DataFrame - Final_df 和 Cust_LCK。在 Final_df DataFrame 中,我有一列名为“Cust Group”的空白值和另一列具有唯一帐号 - “Acct #”(两个数据帧之间的链接)。另一个 DataFrame (Cust_LCK) 有一个标题为“Acct #”的列,其中包含唯一的帐号,“Cust Group”包含帐号所属的客户组。

如何填写Final_df中客户群的空白?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以使用pandas.Series.map() 将值从Cust_LCK 映射到Final_df 列。

    import pandas as pd
    
    
    df = pd.DataFrame({'A': [5, 6, 7, 8, 9], 'B': [1, 2, 3, 4, 5]})
    
    Final_df = pd.DataFrame({
        'Acct#'     : range(0, 5),
    })
    
    Final_df['Cust Group'] = ''
    
    Cust_LCK = pd.DataFrame({
        'Acct#'     : range(5, 0, -1),
        'Cust Group': range(10, 15)
    })
    
    Final_df['Cust Group'] = Final_df['Acct#'].map(Cust_LCK.set_index('Acct#')['Cust Group'])
    

    如果Cust_LCK 列的值有重复项,请只保留其中一个与pandas.DataFrame.drop_duplicates()

    Final_df['Cust Group'] = Final_df['Acct#'].map(Cust_LCK.drop_duplicates(subset['Acct#']).set_index('Acct#')['Cust Group'])
    

    如果Cust_LCK 中的重复行具有不同的Cust Group 值,请使用pandas.DataFrame.merge() 保留它们:

    Final_df = Final_df.merge(Cust_LCK[['Acct#', 'Cust Group']], how='left', on=['Acct#']).drop('Cust Group_x', axis=1).rename(columns={'Cust Group_y': 'Cust Group'})
    
    import pandas as pd
    
    
    df = pd.DataFrame({'A': [5, 6, 7, 8, 9], 'B': [1, 2, 3, 4, 5]})
    
    Final_df = pd.DataFrame({
        'Acct#'     : range(0, 5),
    })
    
    Final_df['Cust Group'] = ''
    
    print(Final_df)
    
    '''
       Acct# Cust Group
    0      0
    1      1
    2      2
    3      3
    4      4
    '''
    
    Cust_LCK = pd.DataFrame({
        'Acct#'     : [4, 4, 3, 2, 1],
        'Cust Group': range(10, 15)
    })
    Cust_LCK['Group'] = ''
    
    
    print(Cust_LCK)
    
    '''
       Acct#  Cust Group Group
    0      4          10
    1      4          11
    2      3          12
    3      2          13
    4      1          14
    '''
    
    Final_df = Final_df.merge(Cust_LCK[['Acct#', 'Cust Group']], how='left', on=['Acct#']).drop('Cust Group_x', axis=1).rename(columns={'Cust Group_y': 'Cust Group'})
    
    print(Final_df)
    
    '''
       Acct#  Cust Group
    0      0         NaN
    1      1        14.0
    2      2        13.0
    3      3        12.0
    4      4        10.0
    5      4        11.0
    '''
    

    如果您不想在合并后删除和重命名列。在合并之前删除Final_dfCust Group 列。

    【讨论】:

    • 没用。引发索引错误。 InvalidIndexError:重新索引仅对具有唯一值的索引对象有效
    • @wleonard 如果Acct # 的值是唯一的,则不会出现此错误。
    • @wleonard 编辑了我的答案,看看它是否满足您的需要。
    猜你喜欢
    • 2020-10-16
    • 1970-01-01
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    相关资源
    最近更新 更多