首页 > 解决方案 > 如何将 Excel 负值转换为 Pandas 负值

问题描述

我是python pandas的初学者。我正在研究一个名为 fortune_company 的数据集。数据集如下所示。

在此处输入图像描述 在 Profits_In_Million 列的这个数据集中,有一些负值,用红色和括号表示。

但在熊猫中它显示如下截图

在此处输入图像描述

我试图使用下面的代码转换数据类型 Profits_In_Million 列

import pandas as pd
fortune.Profits_In_Million = fortune.Profits_In_Million.str.replace("$","").str.replace(",","").str.replace(")","").str.replace("(","-").str.strip()
fortune.Profits_In_Million.astype("float")

但我收到以下错误。请有人帮我一个。如何将此字符串数据类型转换为浮点数。

ValueError: could not convert string to float: '-'

标签: python-3.xpandas

解决方案


假设您无法控制 Excel 中的单元格格式,则可以使用converterskwarg :read_excel

转换器:字典,默认无

用于转换某些列中的值的函数的字典。键可以是整数或列标签,值是接受一个输入参数的函数,即 Excel 单元格内容,并返回转换后的内容。

来自read_excel文档

def negative_converter(x):
    # a somewhat naive implementation
    if '(' in x:
        x = '-' + x.strip('()')
    return x


df = pd.read_excel('test.xlsx', converters={'Profits_In_Million': negative_converter})
print(df)
#      Profits_In_Million
#    0              $1000
#    1             -$1000

但是请注意,此列的值仍然是字符串,而不是数字 ( int/ float)。您可以很容易地实现转换negative_converter(删除美元符号,很可能还有逗号),例如:

def negative_converter(x):
    # a somewhat naive implementation
    x = x.replace('$', '')
    if '(' in x:
        x = '-' + x.strip('()')
    return float(x)

df = pd.read_excel('test.xlsx', converters={'Profits_In_Million': negative_converter})
print(df)
#      Profits_In_Million
#    0             1000.0
#    1            -1000.0

推荐阅读