【问题标题】:Replace values in pandas column with default value for missing keys将 pandas 列中的值替换为缺失键的默认值
【发布时间】:2019-05-05 05:46:39
【问题描述】:

我有多个简单的函数需要在我的数据框的某些列的每一行上实现。数据框非常像,超过 1000 万行。我的数据框是这样的:

Date      location   city        number  value
12/3/2018   NY       New York      2      500
12/1/2018   MN       Minneapolis   3      600
12/2/2018   NY       Rochester     1      800
12/3/2018   WA       Seattle       2      400

我有这样的功能:

def normalized_location(row):
    if row['city'] == " Minneapolis":
        return "FCM"
    elif row['city'] == "Seattle":
        return "FCS"
    else:
        return "Other"

然后我使用:

df['Normalized Location'] =df.apply (lambda row: normalized_location (row),axis=1)

这非常慢,我怎样才能提高效率?

【问题讨论】:

    标签: python pandas dataframe lambda replace


    【解决方案1】:

    我们可以使用mapdefaultdict 使这个BLAZING 更快。

    from collections import defaultdict
    
    d = defaultdict(lambda: 'Other')
    d.update({"Minneapolis": "FCM", "Seattle": "FCS"})
    
    df['normalized_location'] = df['city'].map(d)
    
    print(df)
            Date location         city  number  value normalized_location
    0  12/3/2018       NY     New York       2    500               Other
    1  12/1/2018       MN  Minneapolis       3    600                 FCM
    2  12/2/2018       NY    Rochester       1    800               Other
    3  12/3/2018       WA      Seattle       2    400                 FCS
    

    ...为了性能原因绕过fillna 调用。这种方法很容易推广到多个替换。

    【讨论】:

    • 我可以谷歌 (stackoverflow.com/questions/19798153/…),但您能简要解释一下或链接到defaultdict(lambda: 'Other') 行的解释吗?如果该位置不在dict 中,则将其设置为Other?
    • @Evan 你知道了,当key不存在时,字典返回“Other”。
    • 这真的很快。谢谢!!
    【解决方案2】:

    您可能想使用np.select

    conds = [df.city == 'Minneapolis', df.city == 'Seattle']
    choices = ['FCM', 'FCS']
    
    df['normalized_location'] = np.select(conds, choices, default='other')
    
    >>> df
            Date location         city  number  value normalized_location
    0  12/3/2018       NY     New York       2    500               other
    1  12/1/2018       MN  Minneapolis       3    600                 FCM
    2  12/2/2018       NY    Rochester       1    800               other
    3  12/3/2018       WA      Seattle       2    400                 FCS
    

    【讨论】:

    • 每天学习新东西+1
    • 只是一个小提示,对于每个替换,您都需要计算一个单独的掩码。
    【解决方案3】:

    试试这个:

    map_ = {'Minneapolis':'FCM', 'Seattle':'FCS'}
    df.loc[:,'city'] = df.loc[:,'city'].map(map_).fillna('Other')
    
    print(df)
        Date      location  city    number  value
    0  12/3/2018       NY  Other       2    500
    1  12/1/2018       MN    FCM       3    600
    2  12/2/2018       NY  Other       1    800
    3  12/3/2018       WA    FCS       2    400
    

    【讨论】:

      【解决方案4】:

      您可以使用嵌套的np.where()

      df['city'] = np.where(df['city']=='Minneapolis', 'FCM', np.where(df['city']=='Seattle', 'FCS', 'Other'))
      

      【讨论】:

      • 这比np.select的嵌套深度快3。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2020-12-13
      • 1970-01-01
      • 2022-01-05
      • 2020-10-07
      • 2019-01-28
      相关资源
      最近更新 更多