首页 > 解决方案 > 使用其位置/索引转换列的类型

问题描述

我正在.csv从文件夹中读取一些文件。我正在尝试使用每个文件创建数据框列表。

在某些文件中,列值,即Quantityinstrfloat64数据类型。因此,我试图将该列quantity转换为int.

我正在使用其位置/索引访问我的列(出于自动化目的)。

在列表中的所有数据帧中,这是其中之一,

    CustName    ProductID   Quantity
0   56MED       110         '1215.0'
1   56MED       112         5003.0
2   56MED       114         '6822.0'
3   WillSup     2285        5645.0
4   WillSup     5622        6523.0
5   HammSup     9522        1254.0
6   HammSup     6954        5642.0

因此,我的长相是这样的,

df.columns[2] = pd.to_numeric(df.columns[2], errors='coerce').astype(str).astype(np.int64)

我正进入(状态,

TypeError:索引不支持可变操作

在此之前,我尝试过,

df.columns[2] = pd.to_numeric(df.columns[2], errors='coerce').fillna(0).astype(str).astype(np.int64)

但是,我得到了这个错误,

AttributeError:“numpy.float64”对象没有属性“fillna”

有些帖子直接使用列名,但不使用列位置。如何将我的列转换为int使用列位置/索引pnadas

我的pandas版本

print(pd.__version__)
>> 0.23.3

标签: pythonpython-3.xpandastype-conversion

解决方案


df.columns[2]返回一个标量,在本例中是一个字符串。

要访问系列,请使用df['Quantity']df.iloc[:, 2],甚至df[df.columns[2]]。如果你确定你有应该是整数的数据,而不是重复的转换,使用downcast='integer'.

所有这些都是等价的:

df['Quantity'] = pd.to_numeric(df['Quantity'], errors='coerce', downcast='integer')

df.iloc[:, 2] = pd.to_numeric(df.iloc[:, 2], errors='coerce', downcast='integer')

df[df.columns[2]] = pd.to_numeric(df[df.columns[2]], errors='coerce', downcast='integer')

推荐阅读