简体   繁体   English

在python / pandas中将字符串更改为整数

[英]Change string to integer in python / pandas

I am trying to change a string to a float value in a dataframe. 我正在尝试将字符串更改为数据帧中的浮点值。

#showing dataframe for illustration`

IN: df2[:5]

OUT:     TRD_EXCTN_DT   ASCII_RPTD_VOL_TX
    0    08/13/2010      1000000
    1    08/16/2010      1MM+
    2    08/16/2010      369000
    3    08/16/2010      1MM+
    4    08/16/2010      1MM+

output concatenates the string even though I thought I had changed it to a float. 即使我以为我已将其更改为浮点数,输出也会将字符串连接起来。 I need to operate on the number so a string does not work. 我需要对数字进行操作,因此字符串不起作用。

IN: df2.loc[df2['ASCII_RPTD_VOL_TX'] == '1MM+', 'ASCII_RPTD_VOL_TX'] = 1000005
df2.ASCII_RPTD_VOL_TX.astype(float)
df2['b'] = df2['ASCII_RPTD_VOL_TX'] + df2['ASCII_RPTD_VOL_TX']
df2[:3]

OUT:        TRD_EXCTN_DT   ASCII_RPTD_VOL_TX       b
    0        08/13/2010      1000000         10000001000000
    1        08/16/2010      1000005         2000010
    2        08/16/2010      369000          369000369000`

also, 也,

In[22]:df2.dtypes

Out[22]:TRD_EXCTN_DT         object
ASCII_RPTD_VOL_TX    object
b                    object
dtype: object

You want to change your second line to df2['ASCII_RPTD_VOL_TX']=df2.ASCII_RPTD_VOL_TX.astype(float) . 您想将第二行更改为df2['ASCII_RPTD_VOL_TX']=df2.ASCII_RPTD_VOL_TX.astype(float)

The reason you are getting strange result is that your 1st and 3rd row, ASCII_RPTD_VOL_TX column cells are still in str . 您得到奇怪结果的原因是您的第一行和第三行ASCII_RPTD_VOL_TX列单元格仍在str + is doing string concatenate there for those cells. +正在为这些单元格concatenate字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM