LoginSignup
36
21

More than 5 years have passed since last update.

pandasのDataFrameの複数列を同時にastypeで型変換

Posted at

知っている人にとっては常識だったのだろうが、.astype()の引数は辞書で指定できる。

from numpy.random import rand
from pandas import DataFrame

df = DataFrame(rand(3, 3), columns=[list('abc')])
df.dtypes
a    float64
b    float64
c    float64
dtype: object
print(df.astype({'a': int, 'c': str}))
   a         b                 c
0  0  0.692601   0.0963216888725
1  0  0.873724  0.00960078591002
2  0  0.536855    0.639548536613
print(df.astype({'a': int, 'c': str}).dtypes)
a      int64
b    float64
c     object
dtype: object
36
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
21