一、数据载入及初步观察
首先是下载数据集,这里使用Kaggle的 ReliefWeb Crisis Figures Data.
1. 数据载入
1.1 导入模块
# 安装numpy 和 pandas
pip install numpy
pip install pandas
import numpy as np
import panads as pd
1.2 载入数据
# 相对路径
df = pd.read_csv('Data_ ReliefWeb Crisis Figures Data - historical_figures.csv')
# 绝对路径
df = pd.read_csv('/Users/0202zc/Desktop/hands-on-data-analysis/Data_ ReliefWeb Crisis Figures Data - historical_figures.csv')
显示前三行:
注:.csv
和.tsv
格式的区别
- csv 以半角逗号 ‘,’ 作为分割符
- tsv 以制表符 ‘\t’ 作分隔符,且IANA规定的标准格式中,字段值不允许出现 ‘\t’
1.3 划分1000行为一个模块,并逐块读取
使用pandas处理大文件,通常需要分块处理读取部分数据,以提高效率。
chunker = pd.read_csv('Data_ ReliefWeb Crisis Figures Data - historical_figures.csv', chunksize=1000)
1.4 修改表头为中文
df = pd.read_csv('Data_ ReliefWeb Crisis Figures Data - historical_figures.csv', names=['危机ID', '危机索引', '国家名称', '国家代号', '难民类型', '难民来源', '难民人数', '日期', '链接'], index_col='危机ID', header=0)
df.head()
这里自己在csv中添加了编号一列,然后在jupyter中执行第一列为索引。
注:这里还可以使用DataFrame读取表格,然后再修改列名称1
2. 观察数据
2.1 查看表结构信息
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 13362 entries, 1 to 13362
Data columns (total 8 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 危机索引 13362 non-null int64
1 国家名称 13362 non-null object
2 国家代号 13362 non-null object
3 难民类型 13362 non-null object
4 难民来源 13362 non-null object
5 难民人数 13362 non-null int64
6 日期 13362 non-null object
7 链接 13350 non-null object
dtypes: int64(2), object(6)
memory usage: 939.5+ KB
2.2 查看表格前10行和后15行的数据
df.head(10)
df.tail(15)
2.3 判断空数据,返回True或False
提前删除一些数据,然后在jupyter中重新读文件:
df.isnull().head()
3. 保存数据
# 不同的操作系统保存后会有乱码,此时可加入 encoding='GBK' 或 encoding='utf-8' 等
df.to_csv('historical_figures_chinese.csv', encoding='utf-8')
二、pandas 基础
老规矩,导入模块:
import numpy as np
import pandas as pd
1. 数据的属性
1.1 DataFrame 和 Series
pandas中有两种数据类型:DataFrame和Series2
DataFrame | Series |
---|---|
相当于表格,有行列表头 | 类似于数组 numpy.array |
pandas.DataFrame(data) | pandas.Series(data) |
用sort或者sort_index排序 | 用Series.order() 排序 |
![]() | ![]() |
1.2 使用DataFrame
# 载入文件
# 载入csv文件
df = pd.read_csv('historical_figures_chinese.csv')
df.head(3)
# 查看指定列的所有值
df['难民人数'].head(3)
0 9000000
1 7400000
2 8100000
Name: 难民人数, dtype: int64
现删除测试集 test.csv 多余的列:
# 这种方法只对一次执行后有效,不修改原始文件数据
del test['列名']
列的去重更多方法参考 《pandas去重和删除空值列或行》,如:删除缺省值的
dropna
方法
# 隐藏指定列,同样是临时有效
df.drop(['国家名称', '危机索引', '国家代号', '链接'], axis=1).head(3)
若要完全删除数据结构,使用
inplace=True
,即覆盖原数据
1.3 筛选:丢弃无用信息
# 筛选出难民人数在 3800000 到 9000000 之间的数据,命名为 “count”
count = df[(df["难民人数"]>3800000) & (df["难民人数"]<9000000)]
count.head(10)
# 显示count数据中第100、105、109行的指定列数据【loc方法】
count.loc[[100, 105, 109], ['国家名称', '难民人数', '日期']]
注:在删除掉空数据后,索引间断。使用 reset_index()
重置索引,可以获得新的连续索引。
# 显示count数据中第100、105、109行的指定列数据【iloc方法】
count.iloc[[100, 105, 109], [2, 6, 7]]
loc | iloc |
---|---|
指定列名 | 指定列索引 |
三、探索性数据分析
1. 排序
# 构建一个2*4的二维数组,索引列指定为2、1
frame = pd.DataFrame(np.arange(8).reshape((2, 4)), index=['2', '1'], columns=['d', 'a', 'b', 'c'])
# 根据某列值升序排列
frame.sort_values(by='c', ascending=True)
# 按行索引升序排序
frame.sort_index()
# 按列索引升序排序
frame.sort_index(axis=1)
# 同时让两列降序排序
frame.sort_values(by=['a', 'c'], ascending=False)
使用外部数据排序
text.sort_values(by=['难民人数', '难民类型'], ascending=False).head(5)
2. 利用Pandas进行算数计算
两个DataFrame相加返回一个新的DataFrame,行列对应相加,无对应的为NAN
统计每个国家的人道主义危机数
统计每个国家的难民类型
3. 利用Pandas describe() 查看数据统计信息
text['难民人数'].describe()
count 1.336200e+04
mean 7.631596e+05
std 1.909107e+06
min 0.000000e+00
25% 2.204550e+04
50% 1.194555e+05
75% 5.200040e+05
max 2.726232e+07
Name: 难民人数, dtype: float64