python - 读取外部 Excel 文件后,我的 Pandas 数据框列中的值不准确
问题描述
我已将以下文件读入 Pandas 数据框:http: //unstats.un.org/unsd/environment/excel_file_tables/2013/Energy%20Indicators.xls
我之前在 Excel 中查看过该文件,单元格包含字符串 ' ...'(正好 3 个点)来表示缺失值。
我的问题是,在将文件读入名为“energy”的 Pandas 数据框后,一些缺失值不再用 Excel 文档中定义的“...”表示,而是一系列更多的点,例如: '.................................. .'. 这使得energy.replace('...', np.nan, inplace=True)
操作不准确,因为并非所有缺失值都被替换。
谁能解释为什么会发生这种行为,以及用 Pandas 纠正它的最佳方法是什么?
这是我的代码:
import pandas as pd
import numpy as np
import re
# Read excel file
energy = pd.read_excel('http://unstats.un.org/unsd/environment/excel_file_tables/2013/Energy%20Indicators.xls',
skiprows = 17,
skipfooter = 38)
# Drop the first 2 unnecessary columns
energy.drop(['Unnamed: 0', 'Unnamed: 1'], axis=1, inplace=True)
# Rename the remaining columns
col_names = ['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable']
energy.columns = col_names
# Convert energy supply to gigajoules
energy['Energy Supply'] = energy['Energy Supply'] * 1000000
# Replace missing values
energy.replace('...', np.nan, inplace=True)
# Replace country names according to provided to specifications
energy['Country'].replace({
'Republic of Korea': 'South Korea',
'China, Hong Kong Special Administrative Region': 'Hong Kong',
'United Kingdom of Great Britain and Northern Ireland': 'United Kingdom',
'United States of America': 'United States'
}, inplace=True)
energy.head()
上面的代码导致以下数据框: 带有意外值的数据框被圈出
解决方案
na_values
第一个解决方案是使用参数read_excel
:
energy = pd.read_excel('http://unstats.un.org/unsd/environment/excel_file_tables/2013/Energy%20Indicators.xls',
skiprows = 17,
skipfooter = 38,
na_values='...')
使用 - 正则表达式的另一种解决方案replace
更改^\.+$
为仅将多个点替换为NaN
s:
^
用于转义点的字符串
\
开头,因为通常在正则表达式中使用点符号来匹配任何字符
+
用于一个或多个点
$
用于字符串结尾
energy.replace(r'^\.+$', np.nan, inplace=True, regex=True)
推荐阅读
- terraform - Terraform azure 不兼容的提供程序版本
- python - 没有“Errno 2”,无法导航到 Google Colab 中的特定文件夹
- php - 如何从数组值计算不同的时间
- python - 制作一个函数来进行傅里叶逆变换
- perl - 如何在 Perl 中提取列表的最后一个元素?
- r - terra 管理数字精度:写入文件时修改十进制栅格值
- python - 在 for 循环语句中返回字典列表
- php - Laravel 8.0 为管理员和非管理员角色设置路由的最佳实践
- node.js - 如何解决 Nodejs google-auth-library 无效令牌签名错误?
- javascript - JavaScript-创建一个函数来大写字符串的第一个字母