有几个浮点型列,我想将所有浮点型列转换为整数型。
在了解这些浮点型列的列名之前,如何在一行中将它们全部转换为整数类型?
您可以首先使用select_dtypes
选择类型,然后对其进行round
舍入,最后使用支持Nullable Int dtype的df.astype
转换为Int64
:
m = df.select_dtypes(np.number)
df[m.columns]= m.round().astype('Int64')
# say df is the dataframe
for c in df.columns:
if df[c].dtype == np.float:
df[c] = df[c].astype(int)
df.round().astype('Int64')
吗?你也可以查看df.select_dtypes()
来仅包含数字列,如果不确定的话,请花时间阅读这篇关于如何提供一个出色的 Pandas 示例的帖子:how to provide a great pandas example,以及如何提供一个 minimal, complete, and verifiable example 并相应地修改你的问题。 - ankyselect_dtypes
的答案吗?谢谢。 - DennisLim = df.select_dtypes(np.number)
,df[m.columns]= m.round().astype('Int64')
。你可以在这里了解有关Int64
的信息,它也可以处理 NaN 值。 - anky