【问题标题】:Convert a Column's type using its position/index使用其位置/索引转换列的类型
【发布时间】:2019-02-04 20:41:53
【问题描述】:

我正在从一个文件夹中读取一些.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)

我明白了,

TypeError:索引不支持可变操作

在此之前,我试过了,

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

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

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

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

我的pandas 版本

print(pd.__version__)
>> 0.23.3

【问题讨论】:

  • 试试,df[df.columns[3]]
  • df.columns[3] 是指向列标题的,这不是你想做的。你可以使用df.iloc[:,3]
  • @ScottBoston 我仍然收到AttributeError: 'numpy.float64' object has no attribute 'fillna' 的建议 :(
  • 您能否添加一些数据和完整代码以生成此错误。

标签: python python-3.x pandas type-conversion


【解决方案1】:

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

【讨论】:

  • 谢谢,但不确定您是否在帖子中尝试过我的df,我得到NaN 字符串值,即'1215.0'。此外,数据框的 dtype 从object 更改为float64 而不是int。任何想法为什么?
【解决方案2】:

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

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

或来自@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    相关资源
    最近更新 更多