使用iloc更改特定列的dtype

时间:2018-09-18 22:00:37

标签: python python-3.x pandas dataframe

我想通过iloc更改DataFrame中某些列的dtype。但是当我尝试这样做时,dtype不会改变(它仍然是对象):

import pandas as pd
names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']
df = pd.read_csv('iris.csv', names=names, header=None)
df = df[1:]

In [11]: df.head()
Out[11]:
   sepal-length  sepal-width  petal-length  petal-width   class
1           5.1          3.5           1.4          0.2  setosa
2           4.9          3.0           1.4          0.2  setosa
3           4.7          3.2           1.3          0.2  setosa
4           4.6          3.1           1.5          0.2  setosa
5           5.0          3.6           1.4          0.2  setosa


In [12]: df.iloc[:,:-1] = df.iloc[:,:-1].astype(float)
# No Error

In [13]: df.dtypes  # still object dtype
Out[13]:
sepal-length    object
sepal-width     object
petal-length    object
petal-width     object
class           object
dtype: object

注意:我可以在没有iloc的情况下执行此操作,但是它太长了:

df[['sepal-length', 'sepal-width', 'petal-length', 'petal-width']] = df[['sepal-length', 'sepal-width', 'petal-length', 'petal-width']].astype(float)

3 个答案:

答案 0 :(得分:4)

您可以使用infer_objects

In [11]: df.infer_objects()
Out[11]:
   sepal-length  sepal-width  petal-length  petal-width   class
1           5.1          3.5           1.4          0.2  setosa
2           4.9          3.0           1.4          0.2  setosa
3           4.7          3.2           1.3          0.2  setosa
4           4.6          3.1           1.5          0.2  setosa
5           5.0          3.6           1.4          0.2  setosa

In [12]: df.infer_objects().dtypes
Out[12]:
sepal-length    float64
sepal-width     float64
petal-length    float64
petal-width     float64
class            object
dtype: object

问题在于,尽管右侧是正确的:

In [21]: df.iloc[:,:-1].astype(float).dtypes
Out[21]:
sepal-length    float64
sepal-width     float64
petal-length    float64
petal-width     float64
dtype: object

分配df.iloc[:,:-1] =正在更新现有列,并且更改其dtype。

答案 1 :(得分:2)

问题在于使用hMapFile := DllCall("OpenFileMapping", "Ptr", 0xF001F, "Int", 0, "Str", "SharedMemoryName") pBuf := DllCall("MapViewOfFile", "Ptr", hMapFile, "Int", 0x4, "Int", 0, "Int", 0, "Ptr", 512) value := NumGet(pBuf, 8, "UInt") msgbox %value% 。您可以使用常规列索引解决此问题:

iloc

或者:

您可以将df[df.columns[:-1]] = df[df.columns[:-1]].astype(float) 应用于所有这样的列,由于无法转换,它将跳过to_numeric

class

答案 2 :(得分:0)

df.infer_objects()是为机器学习算法(例如XGBoost)准备df的正确方法。大多数csv导入的数据帧都具有'object'dtype,而许多机器学习算法(例如catboost,xgboost等)都不支持它们。要使它们工作,请使用df.infer_objects()

相关问题