首页 文章

用pandas DataFrame中的逗号将数字字符串转换为float

提问于
浏览
48

我有一个DataFrame包含数字作为字符串与数千标记的逗号 . 我需要将它们转换为浮点数 .

a = [['1,200', '4,200'], ['7,000', '-0.03'], [ '5', '0']]
df=pandas.DataFrame(a)

我猜我需要使用locale.atof . 确实

df[0].apply(locale.atof)

按预期工作 . 我得到了一系列花车 .

但是当我将它应用于DataFrame时,我收到一个错误 .

df.apply(locale.atof)

TypeError :(“无法将系列转换为”,在索引0'处发生')

df[0:1].apply(locale.atof)

给出另一个错误:

ValueError :('float()的文字无效:1,200',u'occurred at index 0')

那么,我如何将这个 DataFrame 字符串转换为浮动的DataFrame?

2 回答

  • 86

    如果你是reading in from csv那么你可以使用thousands arg

    df.read_csv('foo.tsv', sep='\t', thousands=',')
    

    该方法可能比作为单独步骤执行操作更有效 .


    你需要先set the locale

    In [ 9]: import locale
    
    In [10]: from locale import atof
    
    In [11]: locale.setlocale(locale.LC_NUMERIC, '')
    Out[11]: 'en_GB.UTF-8'
    
    In [12]: df.applymap(atof)
    Out[12]:
          0        1
    0  1200  4200.00
    1  7000    -0.03
    2     5     0.00
    
  • 12

    您可以使用pandas.Series.str.replace方法:

    df.iloc[:,:].str.replace(',', '').astype(float)
    

    此方法可以删除或替换字符串中的逗号 .

相关问题