首页 > 解决方案 > 读取外部 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()

上面的代码导致以下数据框: 带有意外值的数据框被圈出

标签: pythonpython-3.xpandas

解决方案


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更改^\.+$为仅将多个点替换为NaNs:

^用于转义点的字符串
\开头,因为通常在正则表达式中使用点符号来匹配任何字符
+用于一个或多个点
$用于字符串结尾


energy.replace(r'^\.+$', np.nan, inplace=True, regex=True)

推荐阅读