【发布时间】:2019-02-04 20:41:53
【问题描述】:
我正在从一个文件夹中读取一些.csv 文件。我正在尝试使用每个文件创建数据框列表。
在某些文件中,列值,即Quantity 属于str 和float64 数据类型。因此,我试图将该列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