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

I read the DataFrame.apply docs

DataFrame.apply (func, axis = 0, broadcast = False, raw = False, reduce = None, args = (), ** kwds) ΒΆ Applies a function along the input axis of the DataFrame.

So how can I apply a function to a specific column?

In [1]: import pandas as pd In [2]: data = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]} In [3]: df = pd.DataFrame(data) In [4]: df Out[4]: ABC 0 1 4 7 1 2 5 8 2 3 6 9 In [5]: def addOne(v): ...: v += 1 ...: return v ...: In [6]: df.apply(addOne, axis=1) Out[6]: ABC 0 2 5 8 1 3 6 9 2 4 7 10 

I want to add One to each value in df['A'] , and not to all columns. How to do it using DataFrame.apply .

Thanks for the help!

+8
source share
2 answers

Answer,

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

and maybe you'd better know about the difference in map , applymap , apply .

but if you insist on applying apply , you can try as shown below.

 def addOne(v): v['A'] += 1 return v df.apply(addOne, axis=1) 
+17
source

One easy way would be:

 df['A'] = df['A'].apply(lambda x: x+1) 
+7
source

Source: https://habr.com/ru/post/1245743/


All Articles