如何将Excel负值转换为Pandas负值

时间:2018-12-31 15:34:48

标签: python-3.x pandas

我是python熊猫的初学者。我正在处理一个名为fortune_company的数据集。数据集如下。

enter image description here 在此数据集的Profits_In_Million列中,有一些负值,由红色和括号指示。

但在大熊猫中,其显示如下面的屏幕截图

enter image description here

我正尝试使用以下代码转换数据类型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")

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

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

1 个答案:

答案 0 :(得分:2)

假设您无法控制Excel中的单元格格式,则可以使用converters的{​​{1}} kwarg:

  

转换器:字典,默认为无

     

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

来自read_excel的{​​{3}}。

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