学习pandas的原因
(1)借助pandas可以处理非数值型数据,例如,字符串、时间序列等。
(2)可以处理数值
(3)高性能、易用的数据结构、数据分析工具
pandas常见的数据类型
(1)Series一维,带标签的数组
(2)DataFrame二维,Series容器
pandas.Series
pandas处理数值型数据
默认索引从0开始,可以通过index来指定索引。通过type来获取数据类型。
In [1]: import pandas as pd
In [2]: t=pd.Series([1,2,31,12,3,4])
In [3]: t
Out[3]:
0 1
1 2
2 31
3 12
4 3
5 4
dtype: int64
In [4]: type(t)
Out[4]: pandas.core.series.Series
In [5]: t2=pd.Series([1,2,31,12,4],index=list('abcde'))#指定索引
In [6]: t2
Out[6]:
a 1
b 2
c 31
d 12
e 4
dtype: int64
pandas处理非数值型数据
(1)通过字典的形式来创建索引和数值
In [7]: temp_dict={'name':'xiaohong','age':30,'tel':10086}
In [8]: t3=pd.Series(temp_dict)
In [9]: t3
Out[9]:
name xiaohong
age 30
tel 10086
dtype: object
In [10]: t3.dtype
Out[10]: dtype('O')
In [11]: t2.dtype
Out[11]: dtype('int64')
(2)访问pandas创建的数据
通过**t[‘指定索引’]/t[默认索引]来访问单行数据
通过t[a:b]/t[‘指定索引1’,‘指定索引2’……]**切片方式来访问多行数据
In [7]: temp_dict={'name':'xiaohong','age':30,'tel':10086}
In [8]: t3=pd.Series(temp_dict)
In [9]: t3['age']
Out[9]: 30
In [10]: t3['tel']
Out[10]: 10086
In [11]: t3[1]
Out[11]: 30
In [12]: t3[2]
Out[12]: 10086
In [13]: t3[0]
Out[13]: 'xiaohong'
In [14]: t3[:2]
Out[14]:
name xiaohong
age 30
dtype: object
In [15]: t3[[1,2]]
Out[15]:
age 30
tel 10086
dtype: object
In [16]: t3[['name','tel']]
Out[16]:
name xiaohong
tel 10086
dtype: object
pandas读取外部数据
ps:导入文件
1.打开pycharm,依次点击File、Settings选项;
2.点击打开Project Structure选项;
3.点击Add Content Root选项,根据需要添加源码文件路径即可(如果是csv等可以放入一个文件夹中,再添加文件夹路径)
(1)读取csv文件
#coding=utf-8
import pandas as pd
#pandas读取csv中的文件
df=pd.read_csv('./dogNames2.csv')
print(df)
(2)读取sql数据:pd.read_sql(sql_sentence,connection)
(3)读取mongodb数据
#coding=utf-8
from pymongo import MongoClient
import pandas as pd
client=MongoClient()
collections=client['douban']['tv1']
data=list(collections.find())
print(data)
t1=data[0]
t1=pd.Series(t1)
print(t1)
pandas.DataFrame
DataFrame对象既有行索引,又有列索引
行索引,表明不同行,横向索引,叫index,0轴,axis=0
列索引,表明不同列,纵向索引,叫colums,1轴,axis=1
(1)DataFrame是Series的容器
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: t=pd.DataFrame(np.arange(12).reshape((3,4)))
In [4]: t
Out[4]:
0 1 2 3
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
In [5]: t1=pd.DataFrame(np.arange(12).reshape((3,4)),index=list("abc"),columns=list("defg"))
In [6]: t1
Out[6]:
d e f g
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
(2)DataFrame可以传入字典为数据
方式一:只传入一个字典,字典每一个键对应的值有很多个。
In [8]: d1={'name':['xiaoming','xiaofang'],'age':[10,20],'tel':[10086,10010]}
In [9]: pd.DataFrame(d1)
Out[9]:
name age tel
0 xiaoming 10 10086
1 xiaofang 20 10010
In [10]: type(t1)
Out[10]: pandas.core.frame.DataFrame
方式二:传入一个列表,列表中有多个字典。
ps:若传入的数据存在缺失,那么DataFrame相应位置变为NaN。
In [11]: d2=[{'name':'xiaoming','age':20,'tel':10086},{'name':'xiaofang','tel':10010},{'name':'xiaohong','age':18}]
In [12]: t2=pd.DataFrame(d2)
In [13]: t2
Out[13]:
name age tel
0 xiaoming 20.0 10086.0
1 xiaofang NaN 10010.0
2 xiaohong 18.0 NaN
可以从一组数据中取出需要的关键性数据
data=[{},{},{}] #取关键信息
df=pd.DataFrame(data)
print(df)
DataFrame属性
In [11]: d2=[{'name':'xiaoming','age':20,'tel':10086},{'name':'xiaofang','tel':10010},{'name':'xiaohong','age':18}]
In [12]: t2=pd.DataFrame(d2)
In [13]: t2
Out[13]:
name age tel
0 xiaoming 20.0 10086.0
1 xiaofang NaN 10010.0
2 xiaohong 18.0 NaN
In [14]: t2.index #行索引
Out[14]: RangeIndex(start=0, stop=3, step=1)
In [15]: t2.columns #列索引
Out[15]: Index(['name', 'age', 'tel'], dtype='object')
In [16]: t2.values #对象值,二维ndarray数组
Out[16]:
array([['xiaoming', 20.0, 10086.0],
['xiaofang', nan, 10010.0],
['xiaohong', 18.0, nan]], dtype=object)
In [17]: t2.shape #行数 列数
Out[17]: (3, 3)
In [18]: t2.dtypes #列数据类型
Out[18]:
name object
age float64
tel float64
dtype: object
In [19]: t2.ndim #数据维度
Out[19]: 2
In [20]: t2.head(2) #显示头几行,默认5行
Out[20]:
name age tel
0 xiaoming 20.0 10086.0
1 xiaofang NaN 10010.0
In [21]: t2.tail(2) #显示末尾几行,默认5行
Out[21]:
name age tel
1 xiaofang NaN 10010.0
2 xiaohong 18.0 NaN
In [22]: t2.info() #相关信息概览:行数、列数、列索引、列非空值个数、列类型、内存占用
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 name 3 non-null object
1 age 2 non-null float64
2 tel 2 non-null float64
dtypes: float64(2), object(1)
memory usage: 200.0+ bytes
In [23]: t2.describe() #快速综合统计结果:计数、均值、标准差、最大值、四分位数、最小值
Out[23]:
age tel
count 2.000000 2.000000
mean 19.000000 10048.000000
std 1.414214 53.740115
min 18.000000 10010.000000
25% 18.500000 10029.000000
50% 19.000000 10048.000000
75% 19.500000 10067.000000
max 20.000000 10086.000000
DataFrame中排序的方法
使用sort_values()来排序
df.sort_values(by='Count_AnimalName',ascending=False)
#by按照某列进行排序,ascending=False表示逆序,默认升序
print(df.head(5))
DataFrame取行、取列
- 取某一行或者某列
方括号写数组,表示取行,对行进行操作
方括号写字符串,表示取列,对列进行操作
import pandas as pd
#pandas读取csv中的文件
df=pd.read_csv('./dogNames2.csv')
print(df[:20])#取行
print(df['Row_Labels']) #取列
- 同时取行和列
df.loc[ , ]通过标签索引行数据,逗号前面是行,后面是列。
df.iloc[ , ]通过位置获取行数据,逗号前面是行,后面是列。
(1) df.loc[ , ]
In [25]: t3=pd.DataFrame(np.arange(12).reshape(3,4),index=list('abc'),columns=list('wxyz'))
In [26]: t3
Out[26]:
w x y z
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
In [27]: t3.loc['a','z'] #获取某行某列
Out[27]: 3
In [28]: type(t3.loc['a','z'])
Out[28]: numpy.int32
In [29]: t3.loc['a'] #与t3.loc['a',:]一样
Out[29]:
w 0
x 1
y 2
z 3
Name: a, dtype: int32
In [30]: t3.loc['a',:] #获取某行
Out[30]:
w 0
x 1
y 2
z 3
Name: a, dtype: int32
In [31]: t3.loc[:,'y'] #获取某列
Out[31]:
a 2
b 6
c 10
Name: y, dtype: int32
In [32]: t3.loc[['a','c']] #利用输入列表形式来获取多行
Out[32]:
w x y z
a 0 1 2 3
c 8 9 10 11
In [34]: t3.loc[:,['x','z']] #利用输入列表形式来获取多列
Out[34]:
x z
a 1 3
b 5 7
c 9 11
In [36]: t3.loc[['a','c'],['x','z']]#获取多行多列,冒号在loc里是闭合的,也就是会取到’c‘和’z‘这块
Out[36]:
x z
a 1 3
c 9 11
(2)df.iloc[ , ]
In [37]: t3.iloc[1] #获取第二行
Out[37]:
w 4
x 5
y 6
z 7
Name: b, dtype: int32
In [38]: t3.iloc[1,:] #与t3.iloc[1]一样
Out[38]:
w 4
x 5
y 6
z 7
Name: b, dtype: int32
In [39]: t3.iloc[:,2] #获取第三列
Out[39]:
a 2
b 6
c 10
Name: y, dtype: int32
In [40]: t3.iloc[:,[2,1]] #获取第三、二列
Out[40]:
y x
a 2 1
b 6 5
c 10 9
In [41]: t3.iloc[[0,2],[2,1]] #获取多行多列
Out[41]:
y x
a 2 1
c 10 9
In [42]: t3.iloc[1:,:2] #获取第二行之后,第三列之前的所有数据
Out[42]:
w x
b 4 5
c 8 9
In [43]: t3.iloc[1:,:2]=30 #更改数据
In [44]: t3
Out[44]:
w x y z
a 0 1 2 3
b 30 30 6 7
c 30 30 10 11
In [45]: t3.iloc[1:,:2]=np.nan #不会报错,因为在DataFrame里会自动将数据转换为float类型
In [46]: t3
Out[46]:
w x y z
a 0.0 1.0 2 3
b NaN NaN 6 7
c NaN NaN 10 11
布尔索引
&且 |或
多个条件得使用and符号&、or符号|,不同条件直接需要用括号括起来
#pandas读取csv中的文件
df=pd.read_csv('./dogNames2.csv')
print(df[(800<df['Count_AnimalName'])&(df['Count_AnimalName']<1000)])
print(df[(df['Row_Labels'].str.len()>4)&(df['Count_AnimalName']>700)]) #字符串长度.str.len()
缺失数据的处理
数据缺失的情况
(1)空,None等,在pandas是NaN(和np.nan一样)
(2)让其为0
关于NaN的处理方式:
首先判断数据是否为NaN: pd.isnull(df)、pd.notnull(df),其次对其处理。
(1) 删除NaN所在的行列dropna(axis=o,how=‘any’,inplace=False)
how默认any,意为只要有nan的行就会被删掉;all意为全部为nan的行就会被删掉,inplace=True意为原地替换,就地修改。
(2) 填充数据
t.fillna(0)填充数字0
t.fillna(t.mean())填充均值
t.fillna(t.median())填充中位数
t[ , ].fillna()可选定某行、某列进行操作
In [2]: import pandas as pd
In [3]: import numpy as np
In [4]: t3=pd.DataFrame(np.arange(12).reshape(3,4),index=list('abc'),columns=list('wxyz'))
In [5]: t3
Out[5]:
w x y z
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
In [6]: t3.iloc[1:,:2]=np.nan
In [7]: t3
Out[7]:
w x y z
a 0.0 1.0 2 3
b NaN NaN 6 7
c NaN NaN 10 11
In [8]: d2=[{'name':'xiaoming','age':20,'tel':10086},{'name':'xiaofang','tel':10010},{'name':'xiaohong','age':18}]
In [9]: t2=pd.DataFrame(d2)
In [11]: pd.isnull(t3) #判断数据是否为空,是返回True
Out[11]:
w x y z
a False False False False
b True True False False
c True True False False
In [12]: pd.notnull(t3) #判断数据是否不为空,是返回True
Out[12]:
w x y z
a True True True True
b False False True True
c False False True True
In [13]: t3[pd.notnull(t3['w'])] #取t3中w列中不为空的一行
Out[13]:
w x y z
a 0.0 1.0 2 3
In [14]: pd.notnull(t3['w'])
Out[14]:
a True
b False
c False
Name: w, dtype: bool
In [15]: t3.dropna(axis=0) #删除存在NaN的行
Out[15]:
w x y z
a 0.0 1.0 2 3
In [16]: t3.dropna(axis=0,how='all') #删除全部是NaN的行
Out[16]:
w x y z
a 0.0 1.0 2 3
b NaN NaN 6 7
c NaN NaN 10 11
In [17]: t3.dropna(axis=0,how='any') #删除存在NaN的行
Out[17]:
w x y z
a 0.0 1.0 2 3
In [18]: t3.dropna(axis=0,how='all',inplace=True)
In [19]: t3
Out[19]:
w x y z
a 0.0 1.0 2 3
b NaN NaN 6 7
c NaN NaN 10 11
In [20]: t3.dropna(axis=0,how='any',inplace=True) #删除存在NaN的行,并且原地修改。
In [21]: t3
Out[21]:
w x y z
a 0.0 1.0 2 3
In [22]: t2
Out[22]:
name age tel
0 xiaoming 20.0 10086.0
1 xiaofang NaN 10010.0
2 xiaohong 18.0 NaN
In [23]: t2.fillna(0) #将NaN的值填充为0
Out[23]:
name age tel
0 xiaoming 20.0 10086.0
1 xiaofang 0.0 10010.0
2 xiaohong 18.0 0.0
In [24]: t2.mean()
Out[24]:
age 19.0
tel 10048.0
dtype: float64
In [25]: t2.fillna(t2.mean()) #将NaN的值填充为均值
Out[25]:
name age tel
0 xiaoming 20.0 10086.0
1 xiaofang 19.0 10010.0
2 xiaohong 18.0 10048.0
In [26]: t2['age'].fillna(t2['age'].mean())
Out[26]:
0 20.0
1 19.0
2 18.0
Name: age, dtype: float64
In [27]: t2['age']=t2['age'].fillna(t2['age'].mean()) #可指定某列将NaN的值填充为那一列的均值
In [28]: t2
Out[28]:
name age tel
0 xiaoming 20.0 10086.0
1 xiaofang 19.0 10010.0
2 xiaohong 18.0 NaN
In [29]: t2['age'][1]=np.nan
D:\anaconda3\Scripts\ipython:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
In [30]: t2
Out[30]:
name age tel
0 xiaoming 20.0 10086.0
1 xiaofang NaN 10010.0
2 xiaohong 18.0 NaN
In [31]: t2['age'].mean() #在pandas中NaN所在地方不参与计算,不像numpy中与NaN的任何计算全为NaN。
Out[31]: 19.0
3.注意:
处理为0的数据:t[t==0]=np.nan
当然并不是每次为0的数据都需要处理
计算均值等情况时,nan是不参与计算的,但是0会
pandas常用统计方法
#coding=utf-8
import pandas as pd
import numpy as np
import math
file_path='IMDB-Movie-Data.csv'
df=pd.read_csv(file_path)
#print(df.info())
print(df.head(1))
#获取电影的平均评分
print(df['Rating'].mean())
#导演人数
print(len(set(df['Director'].tolist())))
print(len(df['Director'].unique()))
#获取演员人数
temp_actors=df['Actors'].str.split(',').tolist()
actor_list=[i for j in temp_actors for i in j]
print(len(set(actor_list)))
#电影时长的最大值、最小值
max_runtime=df["Runtime (Minutes)"].max()
max_runtime_index=df["Runtime (Minutes)"].argmax()
min_runtime=df["Runtime (Minutes)"].min()
min_runtime_index=df["Runtime (Minutes)"].argmin()
runtime_median=df["Runtime (Minutes)"].median()
print(max_runtime_index)
小练习
问题:想要知道rating(电影评分)、runtime(电影时长)分布情况
#选择图形,直方图
from matplotlib import pyplot as plt
#准备数据
runtime_data=df["Runtime (Minutes)"].values
max_runtime=runtime_data.max()
min_runtime=runtime_data.min()
#计算组距
num_bin=(max_runtime-min_runtime)//5
#绘制直方图
#设置图形大小
plt.figure(figsize=(20,8),dpi=80)
plt.hist(runtime_data,num_bin)
#x轴
plt.xticks(range(min_runtime,max_runtime+5,5))
#展示图形
plt.show()