python-3.x - 如何将 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: '-'
解决方案
假设您无法控制 Excel 中的单元格格式,则可以使用converters
kwarg :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
推荐阅读
- android - 列表项在android中保存上下文的引用是否有好处
- vue.js - Nuxt 中的亚马逊原生购物广告
- node.js - 为 node js 后端 API 创建 Express 前端
- lua - NodeMCU tmr - 'alarm' 的错误参数 #1(预期为布尔值)
- python - 如何在pygame中让图像留在屏幕上?
- mysql - 如何从只有 1 个保存所有关系的多个 mysql 表中获取结果
- r - 中位数 VS 生存中位数(来自 survfit)
- sql - 从 DB2 到 Oracle 的转换:
- list - 如何读取坐标 csv 文件并分解为 E、N、Z 和 Station?
- powershell - 由于无法从 URI 下载,Powershell 无法安装 PowerShellGet