Pandas数据帧中的数据类型转换问题

2024-10-01 11:36:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv文件看起来像这样从一个!猫

,City,region,Res_Comm,mkt_type,Quradate,National_exp,Alabama_exp,Sales_exp,Inventory_exp,Price_exp,Credit_exp
0,Dothan,South_Central-Montgomery-Auburn-Wiregrass-Dothan,Residential,Rural,2010-01-15,2,2,3,2,3,3
1,Dothan,South_Central-Montgomery-Auburn-Wiregrass-Dothan,Residential,Suburban_Urban,2010-07-15,2,2,3,2,2,2
2,Dothan,South_Central-Montgomery-Auburn-Wiregrass-Dothan,Residential,Suburban_Urban,2011-01-15,2,2,2,2,2,2

当我通过read_csv读入时,我得到一个数据帧,所有的…\u exp字段都是个位数,我需要用它来做基本的数学运算(当我使用read table和文件的另一个变体时,它工作得很好)

^{pr2}$

但是,当我做任何数学运算时,我会得到一个类型错误,表明该列是字符串,例如:

df['Credit_exp'] = df['Credit_exp']/2
TypeError: unsupported operand type(s) for /: 'str' and 'int'

我不知道怎么把它转换成整数? 我尝试指定字段类型,比如dtype={'Credit\u exp':np.int32, ... 在文件读取选项中,它不喜欢这样 我试着做一个类型转换 df['Credit_exp']=int(df['Credit_exp']) 给了我:

TypeError: only length-1 arrays can be converted to Python scalars

所以很明显我遗漏了一些东西。。。在


Tags: 文件csvdfreadtypeurbancentralcredit