pandas DataFrame, how to apply function to a specific column?

前端 未结 3 1002
予麋鹿
予麋鹿 2021-01-30 22:57

I have read the docs of DataFrame.apply

DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)¶ Applies function along

相关标签:
3条回答
  • 2021-01-30 23:22

    The answer is,

    df['A'] = df['A'].map(addOne)
    

    and maybe you would be better to know about the difference of map, applymap, apply.

    but if you insist to use apply, you could try like below.

    def addOne(v):
        v['A'] += 1
        return v
    
    df.apply(addOne, axis=1)
    
    0 讨论(0)
  • 2021-01-30 23:24

    One simple way would be:

    df['A'] = df['A'].apply(lambda x: x+1)
    
    0 讨论(0)
  • 2021-01-30 23:30

    you can use .apply() with lambda function to solve this kind of problems.

    Consider, your dataframe is something like this,

    A | B | C
    ----------
    1 | 4 | 7
    2 | 5 | 8
    3 | 6 | 9
    

    The function which you want to apply:

    def addOne(v):
    v += 1
    return v
    

    So if you write your code like this,

    df['A'] = df.apply(lambda x: addOne(x.A), axis=1)
    

    You will get:

    A | B | C
    ----------
    2 | 4 | 7
    3 | 5 | 8
    4 | 6 | 9
    
    0 讨论(0)
提交回复
热议问题