Warning: Undefined variable $position in /home/pystyles/pystyle.info/public_html/wp/wp-content/themes/lionblog/functions.php on line 4897

pandas – apply、applymap、map の使い方

pandas – apply、applymap、map の使い方

概要

pandas の apply、applymap、map の使い方について解説します。

Advertisement

関数一覧

pandas.DataFrame.apply

pandas.DataFrame.apply は、DataFrame の列または行単位で関数を適用する場合に使用します。

DataFrame.apply(self, func, axis=0, raw=False, result_type=None, args=(), **kwds)
引数
名前 デフォルト値
func function
列または行に適用する関数
axis {0 or ‘index’, 1 or ‘columns’} 0
関数を適用する axis 方向
raw bool False
True の場合、関数は ndarray オブジェクトを受け取る。False の場合、関数は Series オブジェクトを受け取る。
result_type {‘expand’, ‘reduce’, ‘broadcast’, None} None
axis=1 のみ有効な設定
  • “expand”: リストの場合は、DataFrame を返す。
  • “reduce”: 返り値の形状に関わらず、Series を返す。
  • “broadcast”: 元の DataFrame の形状に合わせる。
  • None: 関数の返り値に応じて自動で判断する。
args tuple
関数に追加の位置引数を渡す場合は指定する。
**kwds
関数に追加のキーワード引数を渡す場合は指定する。
返り値
名前 説明
Series or DataFrame 関数を適用した結果

サンプルコード

In [1]:
import pandas as pd

df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]})
df
A B
0 1 1
1 2 2
2 3 3
In [2]:
df.apply(lambda x: x ** 2)
A B
0 1 1
1 4 4
2 9 9

axis – 関数を適用する方向を指定する

axis=0 の場合、列方向に適用します。

In [3]:
df.apply(lambda x: x / len(x), axis=0)
A B
0 0.333333 0.333333
1 0.666667 0.666667
2 1.000000 1.000000

axis=1 の場合、列方向に適用します。

In [4]:
df.apply(lambda x: x / len(x), axis=1)
A B
0 0.5 0.5
1 1.0 1.0
2 1.5 1.5

raw – Series の代わりに ndarray を関数に渡す

In [5]:
import numpy as np

df = pd.DataFrame({"A": [2, 1, 3], "B": [1, 3, 2]})
df.apply(lambda x: x.argsort(), raw=True)
A B
0 1 0
1 0 2
2 2 1

result_type – apply() の返り値の形状を設定する

この設定は axis=1 の場合のみ有効です。

In [6]:
df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]})
df.apply(lambda x: (4, 5, 6), result_type="expand", axis=1)
0 1 2
0 4 5 6
1 4 5 6
2 4 5 6
In [7]:
s = df.apply(lambda x: (4, 5, 6), result_type="reduce", axis=1)
print(s)
0    (4, 5, 6)
1    (4, 5, 6)
2    (4, 5, 6)
dtype: object
In [8]:
df.apply(lambda x: 4, result_type="broadcast", axis=1)
A B
0 4 4
1 4 4
2 4 4
In [9]:
df.apply(lambda x: pd.Series([4, 5]), result_type=None, axis=1)
0 1
0 4 5
1 4 5
2 4 5
In [10]:
df.apply(lambda x: 4, result_type=None, axis=1)
0    4
1    4
2    4
dtype: int64

args, kwargs – 関数に渡す追加の引数を設定する

In [11]:
def f(x, a, b):
    return a * x + b


df.apply(f, args=(1, 2))
A B
0 3 3
1 4 4
2 5 5
In [12]:
df.apply(f, a=1, b=2)
A B
0 3 3
1 4 4
2 5 5

pandas.DataFrame.applymap

pandas.DataFrame.applymap は、DataFrame の各要素に対して関数を適用する場合に使用します。

DataFrame.applymap(self, func) → ’DataFrame’
引数
名前 デフォルト値
func callable
1つの値を返す関数

返り値
名前 説明
DataFrame 関数を適用した結果

サンプルコード

In [13]:
df = pd.DataFrame([[123, 1234], [12345678, 12345]])
df
0 1
0 123 1234
1 12345678 12345
In [14]:
df.applymap(lambda x: len(str(x)))
0 1
0 3 4
1 8 5

pandas.Series.apply

pandas.Series.apply は、Series の各値に関数を適用して変換します。

Series.apply(self, func, convert_dtype=True, args=(), **kwds)
引数
名前 デフォルト値
func function
適用する関数
convert_dtype bool True
関数をした適用した結果、最適な型がある場合はその型にキャストする。
args tuple
関数に渡す位置引数がある場合は指定する。
**kwds
関数に渡すキーワード引数がある場合は指定する。
返り値
名前 説明
Series or DataFrame 関数が Series を返す場合、それを各行とした DataFrame を返す

サンプルコード

In [15]:
s = pd.Series([1, 2, 3])
print(s.apply(np.sqrt))
0    1.000000
1    1.414214
2    1.732051
dtype: float64
In [16]:
s = pd.Series([1, 2, 3])

s.apply(lambda x: pd.Series([x, x ** 2, x ** 3]))
0 1 2
0 1 1 1
1 2 4 8
2 3 9 27
Advertisement

pandas.Series.map

pandas.Series.map は、dict または関数で変換方法を指定して、値を変換します。

Series.map(self, arg, na_action=None)
引数
名前 デフォルト値
arg function, collections.abc.Mapping subclass or Series
変換方法
na_action {None, ‘ignore’} None
“ignore” の場合、NaN の値は関数の適用をスキップします。
返り値
名前 説明
Series 変換結果

サンプルコード

args が dict の場合

args に変換前の値を key、変換後の値を value とした dict を指定した場合、その辞書に従い変換します。 辞書に key が存在しない場合は NaN に変換されます。

In [17]:
s = pd.Series(["cat", "dog", np.nan, "rabbit"])

print(s.map({"cat": "kitten", "dog": "puppy"}))
0    kitten
1     puppy
2       NaN
3       NaN
dtype: object

args が関数の場合

args が関数の場合は pandas.Series.apply と同じ挙動になります。

In [18]:
s = pd.Series([1, 2, 3])

print(s.map(lambda x: x ** 2))
0    1
1    4
2    9
dtype: int64
In [ ]:
s = pd.Series([1, 2, 3])

print(s.map(lambda x: x ** 2))

na_action

na_action=True の場合、NaN には関数を適用しません。

In [19]:
print(s.map("I am a {}".format))
print(s.map("I am a {}".format, na_action="ignore"))
0       I am a cat
1       I am a dog
2       I am a nan
3    I am a rabbit
dtype: object
0       I am a cat
1       I am a dog
2              NaN
3    I am a rabbit
dtype: object