使用它的位置/索引转换列的类型

问题描述 投票:0回答:2

我从一个文件夹阅读一些.csv文件。我试图使用每个文件创建数据帧的列表。

在一些文件中的列的值,即Quantity是在strfloat64数据类型。因此,我想在此列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)

我正进入(状态,

类型错误:索引不支持可变操作

在此之前,我试过了,

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
python python-3.x pandas type-conversion
2个回答
2
投票

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')

1
投票

试试这个,你首先需要从你的字符串中删除这些引号,然后使用pd.to_numeric

df.iloc[:, 2] = pd.to_numeric(df.iloc[:, 2].str.strip('\'')).astype(int)

OR从@jpp:

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

输出,df.info():

<class 'pandas.core.frame.DataFrame'>
Int64Index: 7 entries, 0 to 6
Data columns (total 3 columns):
CustName     7 non-null object
ProductID    7 non-null int64
Quantity     7 non-null int32
dtypes: int32(1), int64(1), object(1)
memory usage: 196.0+ bytes

输出:

  CustName  ProductID  Quantity
0    56MED        110      1215
1    56MED        112      5003
2    56MED        114      6822
3  WillSup       2285      5645
4  WillSup       5622      6523
5  HammSup       9522      1254
6  HammSup       6954      5642
© www.soinside.com 2019 - 2024. All rights reserved.