python数据清洗(五)

案例分析
应用学到的所有数据清理技术,以整理从Gapminder Foundation获得的真实世界,混乱的数据集。 完成后,可以拥有干净整洁的数据集,还可以使用Python的强大功能开始处理自己的数据科学项目!

1.1 探索性分析
每当获得新数据集时,第一个任务应该是进行一些探索性分析,以便更好地理解数据并对任何潜在问题进行诊断。

19世纪的Gapminder数据已加载到名为g1800s的DataFrame中。使用pandas方法(如.head(),.info()和.describe())和DataFrame属性(如.columns和.shape)来探索它。

可以看出数据集包含260行,101列,100个数值列, “Life expectancy”是DataFrame中唯一不属于float64类型的列。而且有些国家的值一直没有变过。

1.2 可视化数据
自1800年以来,全球的预期寿命一直在稳步上升。 希望通过Gapminder数据确认这一点。

DataFrame g1800s已预先加载。 你在这个练习中的工作是创建一个散点图,在x轴上的预期寿命为'1800',在y轴上为'1899'的预期寿命。

在这里,目标是直观地检查数据以获得洞察力和错误。 在查看绘图时,请注意散点图是否采用对角线的形式,以及哪些点落在对角线的下方或上方。 这将告知1899年不同国家的预期寿命与1800年相比,将如何改变(或没有改变)。 如果点落在对角线上,则意味着预期寿命保持不变!

# Import matplotlib.pyplot
import matplotlib.pyplot as plt

# Create the scatter plot
g1800s.plot(kind='scatter', x='1800', y='1899')

# Specify axis labels
plt.xlabel('Life Expectancy by Country in 1800')
plt.ylabel('Life Expectancy by Country in 1899')

# Specify axis limits
plt.xlim(20, 55)
plt.ylim(20, 55)

# Display the plot
plt.show()

 正如看到的,有相当多的国家落在对角线上。 事实上,检查DataFrame可以发现,在190世纪,260个国家中有140个国家的预期寿命根本没有变化! 这可能是因为当时无法访问数据。 通过这种方式,可视化数据可以帮助发现洞察并诊断错误。

1.3 思考手头的问题
由于数据集是按国家和年份给出了预期寿命水平数据,因此可以询问有关每年平均预期寿命变化的问题。

但是,在继续之前,确保对数据的以下假设是正确的非常重要:

“预期寿命”是DataFrame的第一列(索引0)。
其他列包含空值或数值。
数值均大于或等于0。
每个国家只有一个实例。
可以编写一个可以应用于整个DataFrame的函数来验证其中的一些假设。 请注意,花时间编写此类脚本也可以帮助处理其他数据集。

def check_null_or_valid(row_data):
    """Function that takes a row of data,
    drops all missing values,
    and checks if all remaining values are greater than or equal to 0
    """
    no_na = row_data.dropna()
    numeric = pd.to_numeric(no_na)
    ge0 = numeric >= 0
    return ge0

# Check whether the first column is 'Life expectancy'
assert g1800s.columns[0] == 'Life expectancy'

# Check whether the values in the row are valid
assert g1800s.iloc[:, 1:].apply(check_null_or_valid, axis=1).all().all()

# Check that there is only one instance of each country
assert g1800s['Life expectancy'].value_counts()[0] == 1

养成像这样测试代码的习惯是一项重要技能。

1.4 组装数据
这里预装了三个DataFrame:g1800s,g1900s和g2000s。 它们分别包含19世纪,20世纪和21世纪的Gapminder预期寿命数据。

本练习中任务是将它们连接到一个名为gapminder的DataFrame中。 这是一个逐行连接,类似于第3部分中连接每月优步数据集的方式。

# Concatenate the DataFrames row-wise
gapminder = pd.concat([g1800s,g1900s,g2000s])

# Print the shape of gapminder
print(gapminder.shape)

# Print the head of gapminder
print(gapminder.head())

从1800年到2016年的所有Gapminder数据现在都包含在一个DataFrame中。

二、数据的初始印象

2.2 检查数据类型
既然数据处于正确的形状,需要确保列具有正确的数据类型。 也就是说,需要确保country是object类型,year是int64类型,而life_expectancy是float64类型。整洁的DataFrame已预先加载为gapminder。

使用.info()方法在IPython Shell中探索它。 请注意,列'year'是object类型。 这是不正确的,因此需要使用pd.to_numeric()函数将其转换为数字数据类型。

# Convert the year column to numeric
gapminder.year = pd.to_numeric(gapminder['year'])

# Test if country is of type object
assert gapminder.country.dtypes == np.object

# Test if year is of type int64
assert gapminder.year.dtypes == np.int64

# Test if life_expectancy is of type float64
assert gapminder.life_expectancy.dtypes == np.float64

由于断言语句没有抛出任何错误,因此可以确保列具有正确的数据类型!

2.3 看着country的拼写
在整理了DataFrame并检查了数据类型之后,数据清理过程中的下一个任务是查看“country”列,看看是否有任何特殊或无效的字符可能需要处理。

可以合理地假设国名将包含:

一组大写字母和大写字母。
单词之间的空格。
任何缩写的期间。
要确认是这种情况,您可以再次利用正则表达式的强大功能。 对于像这样的常见操作,Pandas有一个内置的字符串方法 -  str.contains() - 它采用正则表达式模式,并将其应用于Series,如果匹配则返回True,否则返回False。

因为在这里你想要找到不匹配的值,你必须反转布尔值,这可以使用〜来完成。 然后,可以使用此布尔系列来获取具有无效名称的系列国家/地区。

猜你喜欢

转载自blog.csdn.net/weixin_38300566/article/details/84945338