-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathapply-funcs.py
51 lines (45 loc) · 1.51 KB
/
apply-funcs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import pandas as pd
def apply_function_on_axis_dataframe(df, func, axis=0):
"""Apply a function on a row/column basis of a DataFrame.
Args:
df (pd.DataFrame): Dataframe.
func (function): The function to apply.
axis (int): The axis of application (0=columns, 1=rows).
Returns:
df_return (pd.DataFrame): Dataframe with the applied function.
Examples:
>>> import numpy as np
>>> df = pd.DataFrame(np.array(range(12)).reshape(4, 3), columns=list('abc'))
>>> f = lambda x: x.max() - x.min()
>>> apply_function_on_axis_dataframe(df, f, 1)
0 2
1 2
2 2
3 2
dtype: int64
>>> apply_function_on_axis_dataframe(df, f, 0)
a 9
b 9
c 9
dtype: int64
"""
return df.apply(func, axis)
def apply_function_elementwise_dataframe(df, func):
"""Apply a function on a row/column basis of a DataFrame.
Args:
df (pd.DataFrame): Dataframe.
func (function): The function to apply.
Returns:
df_return (pd.DataFrame): Dataframe with the applied function.
Examples:
>>> import numpy as np
>>> df = pd.DataFrame(np.array(range(12)).reshape(4, 3), columns=list('abc'))
>>> f = lambda x: '%.1f' % x
>>> apply_function_elementwise_dataframe(df, f)
a b c
0 0.0 1.0 2.0
1 3.0 4.0 5.0
2 6.0 7.0 8.0
3 9.0 10.0 11.0
"""
return df.applymap(func)