背景
以下のようにTypeErrorが出て、「あれ、なんでだ?」ってなってたので、記録する。
import pandas as pd
foo = pd.DataFrame([[[1,2],['i','ii']],
[[3,4,5],['iii','iv','v']]], columns=['A','B'])
bar = foo['A'].apply(len, axis=1)
print(bar)
# ---------------------------------------------------------------------------
# TypeError Traceback (most recent call last)
# (中略)
# TypeError: len() takes no keyword arguments
結論
DataFrameの.apply()メソッドにはaxisのキーワード引数があるけど、Seriesにはない。。そりゃそうだ。
import pandas as pd
foo = pd.DataFrame([[[1,2],['i','ii']],
[[3,4,5],['iii','iv', 'v']]], columns=['A','B'])
bar = foo['A'].apply(len) #no axis
print(bar)
# 0 2
# 1 3
# Name: A, dtype: int64
DataFrameの.applyではaxisで適用方向を指定できる。(いい例が思い浮かばないけど)
import pandas as pd
foo = pd.DataFrame([[[1,2],['i','ii']],
[[3,4,5],['iii','iv', 'v']]], columns=['A','B'])
baz = foo.apply(lambda col: [col[0][0], col[1][0]], axis=0)
print(baz)
# A B
# 0 1 i
# 1 3 iii
qux = foo.apply(lambda row: row['A']+row['B'], axis=1)
print(qux)
# 0 [1, 2, i, ii]
# 1 [3, 4, 5, iii, iv, v]
# dtype: object