@@ -4906,46 +4906,33 @@ def apply(self, func, axis=0, broadcast=None, raw=False, reduce=None,
4906
4906
Examples
4907
4907
--------
4908
4908
4909
- We use this DataFrame to illustrate
4910
-
4911
- >>> df = pd.DataFrame(np.tile(np.arange(3), 6).reshape(6, -1) + 1,
4912
- ... columns=['A', 'B', 'C'])
4909
+ >>> df = pd.DataFrame([[4, 9],] * 3, columns=['A', 'B'])
4913
4910
>>> df
4914
- A B C
4915
- 0 1 2 3
4916
- 1 1 2 3
4917
- 2 1 2 3
4918
- 3 1 2 3
4919
- 4 1 2 3
4920
- 5 1 2 3
4911
+ A B
4912
+ 0 4 9
4913
+ 1 4 9
4914
+ 2 4 9
4921
4915
4922
4916
Using a numpy universal function (in this case the same as
4923
4917
``np.sqrt(df)``):
4924
4918
4925
4919
>>> df.apply(np.sqrt)
4926
- A B C
4927
- 0 1.0 1.414214 1.732051
4928
- 1 1.0 1.414214 1.732051
4929
- 2 1.0 1.414214 1.732051
4930
- 3 1.0 1.414214 1.732051
4931
- 4 1.0 1.414214 1.732051
4932
- 5 1.0 1.414214 1.732051
4920
+ A B
4921
+ 0 2.0 3.0
4922
+ 1 2.0 3.0
4923
+ 2 2.0 3.0
4933
4924
4934
4925
Using a reducing function on either axis
4935
4926
4936
4927
>>> df.apply(np.sum, axis=0)
4937
- A 6
4938
- B 12
4939
- C 18
4928
+ A 12
4929
+ B 27
4940
4930
dtype: int64
4941
4931
4942
4932
>>> df.apply(np.sum, axis=1)
4943
- 0 6
4944
- 1 6
4945
- 2 6
4946
- 3 6
4947
- 4 6
4948
- 5 6
4933
+ 0 13
4934
+ 1 13
4935
+ 2 13
4949
4936
dtype: int64
4950
4937
4951
4938
Retuning a list-like will result in a Series
@@ -4954,9 +4941,12 @@ def apply(self, func, axis=0, broadcast=None, raw=False, reduce=None,
4954
4941
0 [1, 2]
4955
4942
1 [1, 2]
4956
4943
2 [1, 2]
4957
- 3 [1, 2]
4958
- 4 [1, 2]
4959
- 5 [1, 2]
4944
+ dtype: object
4945
+
4946
+ >>> df.apply(lambda x: [1,], axis=1)
4947
+ 0 [1]
4948
+ 1 [1]
4949
+ 2 [1]
4960
4950
dtype: object
4961
4951
4962
4952
Passing result_type='expand' will expand list-like results
@@ -4967,9 +4957,6 @@ def apply(self, func, axis=0, broadcast=None, raw=False, reduce=None,
4967
4957
0 1 2
4968
4958
1 1 2
4969
4959
2 1 2
4970
- 3 1 2
4971
- 4 1 2
4972
- 5 1 2
4973
4960
4974
4961
Returning a Series inside the function is similar to passing
4975
4962
``result_type='expand'``. The resulting column names
@@ -4980,23 +4967,17 @@ def apply(self, func, axis=0, broadcast=None, raw=False, reduce=None,
4980
4967
0 1 2
4981
4968
1 1 2
4982
4969
2 1 2
4983
- 3 1 2
4984
- 4 1 2
4985
- 5 1 2
4986
4970
4987
4971
Passing ``result_type='broadcast'`` will ensure the same shape
4988
4972
result, whether list-like or scalar is returned by the function,
4989
4973
and broadcast it along the axis. The resulting column names will
4990
4974
be the originals.
4991
4975
4992
- >>> df.apply(lambda x: [1, 2, 3], axis=1, result_type='broadcast')
4993
- A B C
4994
- 0 1 2 3
4995
- 1 1 2 3
4996
- 2 1 2 3
4997
- 3 1 2 3
4998
- 4 1 2 3
4999
- 5 1 2 3
4976
+ >>> df.apply(lambda x: [1, 2], axis=1, result_type='broadcast')
4977
+ A B
4978
+ 0 1 2
4979
+ 1 1 2
4980
+ 2 1 2
5000
4981
5001
4982
See also
5002
4983
--------
0 commit comments