更新: 您以后不需要转换值,可以在读取CSV时 即时 进行:
In [165]: df=pd.read_csv(url, index_col=0, na_values=['(NA)']).fillna(0)In [166]: df.dtypesOut[166]:Geoname objectComponentName objectIndustryId int64IndustryClassification objectDescription object2004 int642005 int642006 int642007 int642008 int642009 int642010 int642011 int642012 int642013 int642014float64dtype: object
如果您需要将多列转换为数字dtypes,请使用以下技术:
样本来源DF:
In [271]: dfOut[271]: id a b c d e f0 id_3 AAA 6 3 5 8 11 id_9 3 7 5 7 3 BBB2 id_7 4 2 3 5 4 23 id_0 7 3 5 7 9 44 id_0 2 4 6 4 0 2In [272]: df.dtypesOut[272]:id objecta objectb int64c int64d int64e int64f objectdtype: object
将选定的列转换为数字dtypes:
In [273]: cols = df.columns.drop('id')In [274]: df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')In [275]: dfOut[275]: id a b c d e f0 id_3 NaN 6 3 5 8 1.01 id_9 3.0 7 5 7 3 NaN2 id_7 4.0 2 3 5 4 2.03 id_0 7.0 3 5 7 9 4.04 id_0 2.0 4 6 4 0 2.0In [276]: df.dtypesOut[276]:id objecta float64b int64c int64d int64e int64f float64dtype: objectPS,如果要选择 所有
string(
object)列,请使用以下简单技巧:
cols = df.columns[df.dtypes.eq('object')]


