【问题标题】:Convert string into float for multiple columns in data frame将字符串转换为数据框中多列的浮点数
【发布时间】:2019-07-06 03:28:17
【问题描述】:

我正在使用 FIFA 19 的数据集,目前正在尝试将字符串值、工资和释放条款转换为浮点值,例如1.105 亿欧元变成了 110500000。这是我的函数,它将文本作为参数并返回浮点值:

def text_to_num(text):
    d = {'K': 3, 'M': 6, 'B': 9}
    new_text = text[1:]
    if new_text[-1] in d:
        num = new_text[:-1]
        magnitude = new_text[-1]
        return Decimal(num) * 10 ** d[magnitude]
    else:
        return Decimal(new_text)

在单列上应用它很容易,例如价值:

def convert_into_float(data):
    data['Value'] = data['Value'].apply(text_to_num)
    return data

我想知道,如何一次转换所有 3 列而不是使用上述函数三次。

def main():
    # load the data from .csv file, use ID column as index  
    new_data = load_data("data.csv", 'ID') 
    new_data = convert_into_float(new_data)

【问题讨论】:

    标签: python pandas dataframe type-conversion


    【解决方案1】:

    您可以将DataFrame.applymap 与按列表过滤的列一起使用:

    def convert_into_float(data):
        cols = ['col1','col2','col3']
        data[cols] = data[cols].applymap(text_to_num)
        return data
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多