Pandas - replacing column values

后端 未结 3 602
温柔的废话
温柔的废话 2020-11-27 16:58

I know there are a number of topics on this question, but none of the methods worked for me so I\'m posting about my specific situation

I have a dataframe that looks

3条回答
  •  难免孤独
    2020-11-27 17:10

    You can also try using apply with get method of dictionary, seems to be little faster than replace:

    data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)
    

    Testing with timeit:

    %%timeit
    data['sex'].replace([0,1],['Female','Male'],inplace=True)
    

    Result:

    The slowest run took 5.83 times longer than the fastest. This could mean that an intermediate result is being cached.
    1000 loops, best of 3: 510 µs per loop
    

    Using apply:

    %%timeit
    data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)
    

    Result:

    The slowest run took 5.92 times longer than the fastest. This could mean that an intermediate result is being cached.
    1000 loops, best of 3: 331 µs per loop
    

    Note: apply with dictionary should be used if all the possible values of the columns in the dataframe are defined in the dictionary else, it will have empty for those not defined in dictionary.

提交回复
热议问题