Pandas教程——(二)
本次教程你将学会以下几点:
- 由numpy创建数据集
- 导出到txt文件
- 从txt文件读取
- 分析数据
- 展现数据
导包
# Import all libraries needed for the tutorial
import pandas as pd
from numpy import random
import matplotlib.pyplot as plt
import sys #only needed to determine Python version number
import matplotlib #only needed to determine Matplotlib version number
# Enable inline plotting
%matplotlib inline
创建数据
使用numpy创建教程一中使用的数据格式,不过这次加大数据量到1000条。
names = ['Bob','Jessica','Mary','John','Mel']
random.seed(20)
random_names = [names[random.randint(low = 0,high = len(names))] for _ in range(1000)]
birth = [random.randint(low = 0,high = 1000) for _ in range(1000)]
BabyDataSet = list(zip(random_names,birth))
df = pd.DataFrame(BabyDataSet,columns=['name','birth'])
print(df.head(5))
name birth
0 John 305
1 Mary 783
2 Mel 354
3 Mary 975
4 Jessica 621
random.seed()是生成随机数种子,他的作用是使得但我们再次重复调用生成随机数时,产生的结果是一样的。
下面我们将数据导入到txt文件内。
df.to_csv('test.txt',header=False,index=False)
读取数据
吸取教程一的教训,读取数据时加入参数names,自己指定标头的名称。
df = pd.read_csv('test.txt',names=['name','birth'])
print(df.head())
name birth
0 John 305
1 Mary 783
2 Mel 354
3 Mary 975
4 Jessica 621
分析数据
DateFrame对象提供了info()方法来查看df的信息。从下面信息可以看出如下:
- 这是pandas的DataFrame对象数据
- 索引范围从0到999,共1000条数据
- 标头为name的有1000条,类型为object
- 标头为birth的有1000条,类型为int64
- 总共有两种类型,各一个,分别是object、int64
- 数据集大小约为15.7KB
print(df.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 2 columns):
name 1000 non-null object
birth 1000 non-null int64
dtypes: int64(1), object(1)
memory usage: 15.7+ KB
DateFrame对象还提供了unique()方法,用于将指定标头下的值不重复地列出,返回一个array对象。
print(df['name'].unique())
array(['John', 'Mary', 'Mel', 'Jessica', 'Bob'], dtype=object)
描述信息的除了info外,还有一种针对某列的describe()方法。可以获取到信息如下:
- 总共记录1000条
- 不重复值有5个
- 第一条记录的name为Mary
- 该列标头名为name、类型为object
print(df['name'].describe())
count 1000
unique 5
top Mary
freq 218
Name: name, dtype: object
通过groupby()方法可以将重复的字段值整合起来,其他的值相加。下面我们将name整合起来,变成只有五条数据。
name = df.groupby('name')
df = name.sum()
print(df)
name birth
Bob 91025
Jessica 99770
John 99837
Mary 110296
Mel 93222
展现数据
通过plot.bar()方法,将指定的一列数据作为y值,x值默认为索引值。
df['birth'].plot.bar()