栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

pandas数据类型转换,astype与convert

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pandas数据类型转换,astype与convert

共同点: 都可实现数据类型的转换

不同点:
1、astype: 强制转换。将 pandas 对象强制转换为指定的 dtype;在转换为str时,空值也将被强制转换为str类型。

2、convert_dtypes: 转换为最佳类型。将 pandas 对象转换为可能的最佳 dtypes;支持pd.NA的 dtypes

举例:

import pandas as pd
import numpy as np

df = pd.DataFrame(
    {
        "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
        "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")),
        "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")),
        "d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")),
        "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")),
        "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),
    }
)
df
df.applymap(lambda x: type(x))
df.isna()         

# 1、astype(str):空值也会被转换为 str
print(f'{"="*26} astype(atr) {"="*26}')

df_astype = df.astype(str)
df_astype.applymap(lambda x: type(x))
df_astype.isna()        


# 2、convert_dtypes():空值仍然保留
print(f'{"="*60} convert_dtypes() {"="*60}')

df_convert = df.convert_dtypes()
df_convert.applymap(lambda x: type(x))
df_convert.isna()   

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1000793.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号