# 將函式應用於 Pandas DataFrame 中的多個列

Manav Narula 2020年12月19日

``````import pandas as pd
import numpy as np

df = pd.DataFrame(
[[5, 6, 7, 8], [1, 9, 12, 14], [4, 8, 10, 6]], columns=["a", "b", "c", "d"]
)
``````

``````   a  b   c   d
0  5  6   7   8
1  1  9  12  14
2  4  8  10   6
``````

## 使用 `apply()` 將函式應用到 Pandas 中的列

`apply()` 方法允許對整個 DataFrame 應用一個函式，可以跨列或跨行。我們將引數 `axis` 設定為 0 代表行，1 代表列。

``````import pandas as pd
import numpy as np

df = pd.DataFrame(
[[5, 6, 7, 8], [1, 9, 12, 14], [4, 8, 10, 6]], columns=["a", "b", "c", "d"]
)

def x(a):
return a + 1

df_new = df.apply(x, axis=1)

print("The original dataframe:")
print(df)
print("The new dataframe:")
print(df_new)
``````

``````The original dataframe:
a  b   c   d
0  5  6   7   8
1  1  9  12  14
2  4  8  10   6
The new dataframe:
a   b   c   d
0  6   7   8   9
1  2  10  13  15
2  5   9  11   7
``````

``````import pandas as pd
import numpy as np

df = pd.DataFrame(
[[5, 6, 7, 8], [1, 9, 12, 14], [4, 8, 10, 6]], columns=["a", "b", "c", "d"]
)

print("The original dataframe:")
print(df)

def func(x):
return x[0] + x[1]

df["e"] = df.apply(func, axis=1)

print("The new dataframe:")
print(df)
``````

``````The original dataframe:
a  b   c   d
0  5  6   7   8
1  1  9  12  14
2  4  8  10   6
The new dataframe:
a  b   c   d   e
0  5  6   7   8  11
1  1  9  12  14  10
2  4  8  10   6  12
``````

``````import pandas as pd
import numpy as np

df = pd.DataFrame(
[[5, 6, 7, 8], [1, 9, 12, 14], [4, 8, 10, 6]], columns=["a", "b", "c", "d"]
)

print("The original dataframe:")
print(df)

df["e"] = df.apply(lambda x: x.a + x.b, axis=1)

print("The new dataframe:")
print(df)
``````

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.