pandas:DataFrameの複数カラムのデータ型を変更する方法

スポンサーリンク

DataFrameの複数カラムのデータ型を変更する方法

DataFrameの複数カラムのデータ型を変更するにはastypeを使用します。

test.csvのデータ

id,name,count,rating
1,abc,13,4.38
2,defgh,4,8.56
3,ij,0,1.25
4,klmnopq,23,3.49
5,rst,11,0.51
import pandas as pd

df = pd.read_csv("test.csv")
print(df)
#    id     name  count  rating
# 0   1      abc     13    4.38
# 1   2    defgh      4    8.56
# 2   3       ij      0    1.25
# 3   4  klmnopq     23    3.49
# 4   5      rst     11    0.51
print(df.dtypes)
# id          int64
# name       object
# count       int64
# rating    float64
# dtype: object

print(df.astype({"count": "float64", "rating": "int64"}))
#    id     name  count  rating
# 0   1      abc   13.0       4
# 1   2    defgh    4.0       8
# 2   3       ij    0.0       1
# 3   4  klmnopq   23.0       3
# 4   5      rst   11.0       0
print(df.astype({"count": "float64", "rating": "int64"}).dtypes)
# id          int64
# name       object
# count     float64
# rating      int64
# dtype: object