我已将以下文件读入 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()
上面的代码产生了以下数据框: DataFrame with unexpected value circled
请您参考如下方法:
第一个解决方案是在 read_excel 中使用参数 na_values :
energy = pd.read_excel('http://unstats.un.org/unsd/environment/excel_file_tables/2013/Energy%20Indicators.xls',
skiprows = 17,
skipfooter = 38,
na_values='...')
另一种使用 replace 的解决方案 - 将正则表达式更改为 ^\.+$ 以仅将多个点替换为 NaNs:
^ 是字符串的开始
\ 用于转义点,因为通常在正则表达式中使用点符号来匹配任何字符
+ 是一个或多个点
$ 用于字符串结尾
energy.replace(r'^\.+$', np.nan, inplace=True, regex=True)
