pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。pandas提供了大量能使我们快速便捷地处理数据的函数和方法。你很快就会发现,它是使Python成为强大而高效的数据分析环境的重要因素之一。有时候使用numpy可能需要几行代码,但是使用pandas一行就能解决。下面介绍一些pandas库常用的操作。
1.pandas.read_csv
作用:读取csv文件,以DataFrame类型存储
food_info.csv是一个存储食品信息的csv文件,一共有8618种食品,每种食品有36个属性。
import pandas
food_info = pandas.read_csv("food_info.csv")
print(type(food_info))
结果为:
<class 'pandas.core.frame.DataFrame'>
2.head(),tail(),columns和shape
在读取完csv文件之后,还可以通过head(),tail
(),columns()和shape()等方法来获得指定前几行、指定后几行、列名和矩阵大小信息,值得注意的是,head()和tail()方法默认取5行的值,且csv文件中的string类型数据在DataFrame中是以object存储的。
first_rows = food_info.head()
#print(first_rows)
print(food_info.head(1))
#由于输出过于庞大,所以注释掉
#print(food_info.tail())
#print(food_info.columns)
#print(food_info.shape)
结果为:
NDB_No Shrt_Desc Water_(g) Energ_Kcal Protein_(g) \
0 1001 BUTTER WITH SALT 15.87 717 0.85
Lipid_Tot_(g) Ash_(g) Carbohydrt_(g) Fiber_TD_(g) Sugar_Tot_(g) \
0 81.11 2.11 0.06 0.0 0.06
... Vit_A_IU Vit_A_RAE Vit_E_(mg) Vit_D_mcg Vit_D_IU \
0 ... 2499.0 684.0 2.32 1.5 60.0
Vit_K_(mcg) FA_Sat_(g) FA_Mono_(g) FA_Poly_(g) Cholestrl_(mg)
0 7.0 51.368 21.021 3.043 215.0
[1 rows x 36 columns]
3.loc[]
pandas中取某一行和普通矩阵操作不一样,他需要通过使用loc[]来实现:
print(food_info.loc[0])
#也可以取多行,注意,是两个中括号!
#food_info.loc[[1, 3, 5]]
结果为:
NDB_No 1001
Shrt_Desc BUTTER WITH SALT
Water_(g) 15.87
Energ_Kcal 717
Protein_(g) 0.85
Lipid_Tot_(g) 81.11
#后面省略n行
Name: 0, dtype: object
还可以取列,取列操作就和数组下标取元素操作一样了:
ndb_col = food_info["NDB_No"]
print (ndb_col)
#同理,也可以取多列,还是注意,是两个中括号
#zinc_copper = food_info[["Zinc_(mg)", "Copper_(mg)"]]
#print(zinc_copper)
结果为:
0 1001
1 1002
2 1003
3 1004
4 1005
5 1006
#后面省略n行
也可以使用切片来读取想要的连续的行。
4.增加列
例如,将行Iron_(mg)转换为Iron_(g)并增添到源DataFrame中:
iron_grams = food_info["Iron_(mg)"] / 1000
print(food_info.shape)
food_info["Iron_(g)"] = iron_grams
print(food_info.shape)
结果为:
(8618, 36)
(8618, 37)
5.sort_values()
作用:对列进行排序
#默认从小到大排序
#inplace=True:不创建新的对象,直接对原始对象进行修改;
#inplace=False:对数据进行修改,创建并返回新的对象承载其修改结果。
food_info.sort_values("Sodium_(mg)", inplace=True)
print(food_info["Sodium_(mg)"])
#从大到小排序
food_info.sort_values("Sodium_(mg)", inplace=True, ascending=False)
print(food_info["Sodium_(mg)"])
6.pivot_table()
作用:创建透视表。所谓透视表,是一种可以对数据动态排布并且分类汇总的表格格式。下面以泰坦尼克号获救案例作为演示。先简单介绍一下titanic_train.csv:包含891个乘客的ID、获救与否、船舱等级、名字、性别、年龄、兄弟姊妹个数、船票号、船票费、船舱号和登船地点信息。前两个船客信息如下:
现在我们想要知道3种等级的船舱获救的均值,可用如下代码:
passenger_survival = titanic_survival.pivot_table(index="Pclass", values="Survived", aggfunc=np.mean)
print(passenger_survival)
结果如下:
Survived
Pclass
1 0.629630
2 0.472826
3 0.242363
pivot_table()中有三个参数,其中index是以该值为索引,使用values的值来进行aggfunc指定的计算(aggfunc默认值为np.mean,即计算均值)。
还可以用多个values值来进行计算:
#以Embarked(登船地点)为索引,分别计算Fare和Survived的和
port_stats = titanic_survival.pivot_table(index="Embarked", values=["Fare","Survived"], aggfunc=np.sum)
print(port_stats)
结果为:
Fare Survived
Embarked
C 10072.2962 93
Q 1022.2543 30
S 17439.3988 217
7.dropna()
作用:用于滤除缺失数据。
例如:
#丢弃有缺失值的列(一般不会这么做,这样会删掉一个特征)
#drop_na_columns = titanic_survival.dropna(axis=1)
titanic_survival.dropna(axis=0,subset=["Age", "Sex"])
作用就是丢弃‘Age’和‘Sex’这两列中有缺失值的行
8.reset_index()
作用:重置排序之后的索引
一般使用sort_values()方法之后,索引都会被打乱,这个时候就需要使用reset_index()方法。
#drop=True就是把原来的来索引index列去掉,重置index。
#drop=False就是保留源原来的索引,添加重置的index。
itanic_reindexed = new_titanic_survival.reset_index(drop=True)
9.apply()
作用:自定义函数。
例如,想要得到titanic_train.csv中的第100个乘客的信息,我们可以这么做:
def hundredth_row(column):
hundredth_item = column.iloc[99]
return hundredth_item
hundredth_row = titanic_survival.apply(hundredth_row)
print (hundredth_row)
结果如下:
PassengerId 100
Survived 0
Pclass 2
Name Kantor, Mr. Sinai
Sex male
Age 34
SibSp 1
Parch 0
Ticket 244367
Fare 26
Cabin NaN
Embarked S
dtype: object
将自定义的函数放在apply()方法中作为参数。如果自定义函数的参数是column,那么该自定义函数是操作列的;如果参数是row,那么该自定义函数是操作行的,这个时候需要在apply函数中增加一个参数,axis=1,如下:
#获取乘客年龄,并判断是不是成年人
def generate_age_label(row):
age = row["Age"]
if pd.isnull(age):
return "unknown"
elif age < 18:
return "minor"
else:
return "adult"
age_labels = titanic_survival.apply(generate_age_label, axis=1)
print age_labels
10.Series结构
使用pandas读取的csv文件是以DataFrame格式存储,其中的一行或是一列就是Series结构,而Series又是ndarray类型。即DataFrame由Series组成,Series由ndarray组成。