【问题标题】:pandas convert strings to float for multiple columns in dataframe熊猫将字符串转换为数据框中多列的浮点数
【发布时间】:2015-05-06 03:38:14
【问题描述】:

我是 pandas 的新手,想弄清楚如何将格式化为字符串的多个列转换为 float64。目前我正在做以下事情,但似乎 apply() 或 applymap() 应该能够更有效地完成这项任务......不幸的是,我有点太菜鸟了,无法弄清楚如何做。目前,这些值是格式为字符串的百分比,例如 '15.5%'

for column in ['field1', 'field2', 'field3']:
    data[column] = data[column].str.rstrip('%').astype('float64') / 100

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    从 0.11.1 开始(本周发布),replace 有一个新选项可以用正则表达式替换,所以这成为可能

    In [14]: df = DataFrame('10.0%',index=range(100),columns=range(10))
    
    In [15]: df.replace('%','',regex=True).astype('float')/100
    Out[15]: 
    <class 'pandas.core.frame.DataFrame'>
    Int64Index: 100 entries, 0 to 99
    Data columns (total 10 columns):
    0    100  non-null values
    1    100  non-null values
    2    100  non-null values
    3    100  non-null values
    4    100  non-null values
    5    100  non-null values
    6    100  non-null values
    7    100  non-null values
    8    100  non-null values
    9    100  non-null values
    dtypes: float64(10)
    

    而且快一点

    In [16]: %timeit df.replace('%','',regex=True).astype('float')/100
    1000 loops, best of 3: 1.16 ms per loop
    
     In [18]: %timeit df.applymap(lambda x: float(x[:-1]))/100
    1000 loops, best of 3: 1.67 ms per loop
    

    【讨论】:

    • 您能告诉我如何为特定列实现此功能吗? df['Column1'].replace('%','',regex=True).astype('float')/100 没用。
    【解决方案2】:
    df.applymap(lambda x:float(x.rstrip('%'))/100)
    

    【讨论】:

      【解决方案3】:

      在接受的答案中回答评论: 对于特定列,请确保您不要就地执行此操作。

      df['Column1'] = df['Column1'].replace('%','',regex=True).astype('float')/100
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-23
        • 2017-09-17
        • 1970-01-01
        • 2020-10-01
        • 1970-01-01
        相关资源
        最近更新 更多