pandas数据类型转换,astype与convert_dtypes

2023-11-12

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

不同点:
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()   

在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

pandas数据类型转换,astype与convert_dtypes 的相关文章

随机推荐