Robin311
Robin311

Reputation: 253

Is axis=1 meaning row-wise a special case for the apply method in Pandas?

Apparently, this code is supposed to execute the function row-wise for a given dataset. However, according to my knowledge, row-wise operations are done by axis=0, not axis=1.

df.apply(func, axis=1)

Does the apply method somehow operate differently and I just need to know that this is an exception?

Upvotes: 3

Views: 2526

Answers (2)

Donnie
Donnie

Reputation: 68

axis=0 means the functions works along the column and axis=1 means the functions works on the rows. For example

data = pd.DataFrame([[1,2], [3,4]])
data.sum(axis=0)

The result is

0    4
1    6

which is sum along the column

Upvotes: 4

Je Qin Chooi Jay
Je Qin Chooi Jay

Reputation: 1

Another way to see this is that df.sum(axis=1) and df.apply(sum,axis=1) returns an object with the same dimensions.

For example

data = pd.DataFrame([[1,2,4],[3,5,6]])

# applying the sum across columns for each row
# resulting object has dimension nrows x 1
data.sum(axis = 1)

0     7
1    14
dtype: int64

# applying the sum across columns for each row
# resulting object also has dimension nrows x 1
data.apply(sum, axis = 1)

0     7
1    14
dtype: int64

Upvotes: 0

Related Questions