共同点: 都可实现数据类型的转换
不同点:
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()