Pandas 是基于 NumPy 的一种数据处理工具,该工具为了解决数据分析任务而创建。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的函数和方法。这些练习着重DataFrame和Series对象的基本操作,包括数据的索引、分组、统计和清洗。 友情提示:代码虽好,自己动手才算学到。
基本操作
1.导入 Pandas 库并简写为 pd,并输出版本号
import pandas as pdpd.__version__
2.从列表创建 Series
arr = [0, 1, 2, 3, 4]df = pd.Series(arr) # 如果不指定索引,则默认从 0 开始df
3.从字典创建 Series
d = {'a':1,'b':2,'c':3,'d':4,'e':5}df = pd.Series(d)df
4.从 NumPy 数组创建 DataFrame
dates = pd.date_range('today',periods=6) # 定义时间序列作为 indexnum_arr = np.random.randn(6,4) # 传入 numpy 随机数组columns = ['A','B','C','D'] # 将列表作为列名df1 = pd.DataFrame(num_arr, index = dates, columns = columns)df1
5.从CSV中创建 DataFrame,分隔符为;,编码格式为gbk
# df = pd.read_csv('test.csv', encoding='gbk, sep=';')
6.从字典对象data创建DataFrame,设置索引为labels
import numpy as npdata = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'], 'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3], 'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']df = pd.DataFrame(data, index=labels)df
7.显示DataFrame的基础信息,包括行的数量;列名;每一列值的数量、类型
df.info()# 方法二# df.describe()
8.展示df的前3行
df.iloc[:3]# 方法二#df.head(3)
9.取出df的animal和age列
df.loc[:, ['animal', 'age']]# 方法二# df[['animal', 'age']]
10.取出索引为[3, 4, 8]行的animal和age列
df.loc[df.index[[3, 4, 8]], ['animal', 'age']]
11.取出age值大于3的行
df[df['age'] > 3]