python - 使用其位置/索引转换列的类型
问题描述
我正在.csv
从文件夹中读取一些文件。我正在尝试使用每个文件创建数据框列表。
在某些文件中,列值,即Quantity
instr
和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”
有些帖子直接使用列名,但不使用列位置。如何将我的列转换为int
使用列位置/索引pnadas
?
我的pandas
版本
print(pd.__version__)
>> 0.23.3
解决方案
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')
推荐阅读
- mysql - MYSQL 查询计算电子邮件的百分比不为空
- reactjs - 在 react-native 项目中清除 android 和 iOS 中的应用程序数据?
- python-3.x - 运行 Spacy 实体链接示例时出错
- flutter - api 调用将对象转换为可编码对象失败:_LinkedHashMap len:2
- xamarin.forms - (Android 和 iOS)Xamarin - 如何从 WebView 中获取点击/选定的文本或段落?
- oracle - 基于 JDBC Oracle 钱包的连接:内存中的钱包文件夹
- sap - 空值输入参数过滤
- c# - 如何使用 VSIX 扩展实现控制台应用程序
- sql - 无法删除或更新父行:外键约束失败
- java - Spring LocalSessionFactoryBean 不能与 Annontaions 和 HBM 映射一起使用