在pandas dataframe中添加行時設置數據類型

原文鏈接:https://stackoverflow.com/questions/50650850/insert-rows-into-pandas-dataframe-while-maintaining-column-data-types
default = {'name': '', 'age': 0, 'weight': 0.0, 'has_children': False}

row = {'name': 'Cindy', 'age': 42}

df = df.append({**default, **row}, ignore_index=True)

print(df)

結果:
age has_children name weight
0 45 True Bob 143.2
1 40 True Sue 130.2
2 10 False Tom 34.9
3 42 False Cindy 0.0

print(df.dtypes)

age int64
has_children bool
name object
weight float64
dtype: object

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章