- pandas基本介绍
- 为什么要学习pandas
- 什么是 pandas ?
- pandas 的常用数据类型
- Series 一维,带标签数组
- pandas之Series创建
- pandas之Series切片和索引
- pandas之Series的索引和值
- pandas 之读取外部数据
- Dataframe 二维,Series 容器
- pandas 之 Dataframe
- Dataframe和Series有什么关系呢?
- Dataframe传入字典、mongodb数据
- Dataframe 的基本属性
- pandas 之取行或者取列
- dataframe中排序的方法
- 单独研究使用次数前100的数据,应该如何做?
- 同时选择行和列改怎么办?
- pandas 之 loc、iloc
- df.loc 通过**标签**索引行数据
- df.iloc 通过**位置**获取行数据
- pandas 之布尔索引
- panadas 之字符串方法
- 缺失数据的处理
- 在 numpy 中处理 NaN 数据?
- 处理为0的数据:t[t==0]=np.nan
- pandas 常用统计方法
-
numpy能够帮我们处理处理数值型数据,但是这还不够,很多时候,我们的数据除了数值之外,还有字符串,还有时间序列等
-
比如:我们通过爬虫获取到了存储在数据库中的数据
-
比如:之前youtube的例子中除了数值之外还有国家的信息,视频的分类(tag)信息,标题信息等
所以,numpy能够帮助我们处理数值,但是pandas除了处理数值之外(基于numpy),还能够帮助我们处理其他类型的数据
什么是 pandas ?pandas 的常用数据类型 Series 一维,带标签数组 pandas之Series创建pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language.
import numpy as np
import pandas as pd
import string
# Series创建带索引的数组,index可以修改索引形式
t = pd.Series(np.arange(10), index = list("abcdefghij"))
t
'''**********************结果为**********************'''
a 0
b 1
c 2
d 3
e 4
f 5
g 6
h 7
i 8
j 9
dtype: int32
'''**********************查看结构**********************'''
type(t)
'''**********************结果为**********************'''
pandas之Series切片和索引
- 切片:直接传入start end 或者步长即可
- 索引:一个的时候直接传入序号或者 index ,多个的时候传入序号或者 index 的列表
t
'''**********************结果为**********************'''
a 0
b 1
c 2
d 3
e 4
f 5
g 6
h 7
i 8
j 9
dtype: int32
'''*************************************************'''
t[2:10:2]
'''**********************结果为**********************'''
c 2
e 4
g 6
i 8
dtype: int32
'''************************索引:*************************'''
t[1]
'''**********************结果为**********************'''
1
'''*************************************************'''
t[[2,3,6]]
'''**********************结果为**********************'''
c 2
d 3
g 6
dtype: int32
'''*************************************************'''
t[t>4]
'''**********************结果为**********************'''
f 5
g 6
h 7
i 8
j 9
dtype: int32
'''*************************************************'''
t["f"]
'''**********************结果为**********************'''
5
t[["a","f","g"]]
'''**********************结果为**********************'''
a 0
f 5
g 6
dtype: int32
pandas之Series的索引和值
t.index Index(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], dtype='object') t.values array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) type(t.index)type(t.values)
- Series对象本质上由数组构成,一个数组构成对象的键(index, 索引),一个数组构成对象的值(values),键 -> 值
- ndarray 的很多方法都可以运用于 series 类型,比如argmax,clip
- series 具有 where 方法,但是结果和 ndarray 不同
- 当数据存储在csv中,可以直接使用 pd.read_csv
# coding=utf-8
import pandas as pd
# pandas 读取csv中的文件
df = pd.read_csv("./dogNames2.csv")
# 选取动物名称大于800,小于1000的信息
print(df[(800 < df["Count_AnimalName"])|(df["Count_AnimalName"] < 1000)])
结果为:
Row_Labels Count_AnimalName 0 1 1 1 2 2 2 40804 1 3 90201 1 4 90203 1 ... ... ... 16215 37916 1 16216 38282 1 16217 38583 1 16218 38948 1 16219 39743 1 [16220 rows x 2 columns] Process finished with exit code 0Dataframe 二维,Series 容器 pandas 之 Dataframe
-
Dataframe****对象既有行索引,又有列索引
-
行索引,表明不同行,横向索引,叫index,0轴,axis=0
列索引,表名不同列,纵向索引,叫columns,1轴,axis=1
1、Dataframe 是若干有序排列的Series对象。
2、Dataframe 可以看做是含有航索引和列索引的二维数组结构。
3、Dataframe 可以看做是特殊字典,反映了列索引到Series的映射关系。
4、Dataframe 的常见创建方法
-
a、通过Series对象字典创建
-
b、通过字典列表创建。
-
c、用 Numpy 二维数组创建。
# coding=utf-8
from pymongo import MongoClient
import pandas as pd
client = MongoClient()
collection = client["douban"]["tv1"]
data = collection.find()
data_list = []
for i in data:
temp = {}
temp["info"]= i["info"]
temp["rating_count"] = i["rating"]["count"]
temp["rating_value"] = i["rating"]["value"]
temp["title"] = i["title"]
temp["country"] = i["tv_category"]
temp["directors"] = i["directors"]
temp["actors"] = i['actors']
data_list.append(temp)
# t1 = data[0]
# t1 = pd.Series(t1)
# print(t1)
df = pd.Dataframe(data_list)
# print(df)
#显示头几行
print(df.head(1))
# print("*"*100)
# print(df.tail(2))
#展示df的概览
# print(df.info())
# print(df.describe())
print(df["info"].str.split("/").tolist())
Dataframe 的基本属性
pandas 之取行或者取列
dataframe中排序的方法
# coding=utf-8
import pandas as pd
df = pd.read_csv("./dogNames2.csv")
# print(df.head())
# print("*"*50)
# print(df.info())
# print("*"*50)
# dataframe中的排序方法
df = df.sort_values(by="Count_AnimalName",ascending=False)
print(df.head(5))
print("*"*50)
# pandas取行或列的注意点
# - 方括号写数组,表示取行,对行进行操作
# - 方括号写字符串,表示去列索引,对列进行操作
print(df[:20])
print("*"*50)
# 选择具体的某一列
print(df["Row_Labels"])
print("*"*50)
print(type(df["Row_Labels"]))
单独研究使用次数前100的数据,应该如何做?
df_sorted = df.sort_values(by="Count_AnimalName") df_sorted[:100]同时选择行和列改怎么办?
df[:100][" Count_AnimalName "]pandas 之 loc、iloc df.loc 通过标签索引行数据 df.iloc 通过位置获取行数据 pandas 之布尔索引
例‘;使用次数超过800的狗的名字,应该怎么选择?
In : df[df["Count_AnimalName"] > 800]
Out :
Row_Labels Count_AnimalName
1156 BELLA 1195
9140 MAX 1153
2660 CHARLIE 856
3251 COCO 852
12368 ROCKY 823
使用次数超过700并且名字的字符串的长度大于4的狗的名字,应该怎么选择?
In : df[(df["Row_Labels"].str.len() > 4)&(df["Count_AnimalName"]>700)]
Out :
Row_Labels Count_AnimalName
1156 BELLA 1195
2660 CHARLIE 856
12368 ROCKY 823
8552 LUCKY 723
注意
- & 且
- | 或
- 不同条件之间需要用括号括起来
我们的数据缺失通常有两种情况:
- 一种就是空,None等,在pandas是 NaN (和 np.nan 一样)
- 另一种是我们让其为0
在pandas中我们处理起来非常容易
-
判断数据是否为NaN:pd.isnull(df),pd.notnull(df)
-
处理方式
1:删除 NaN 所在的行列 :dropna (axis=0, how=‘any’, inplace=False)
2:填充数据,t.fillna(t.mean()),t.fiallna(t.median()),t.fillna(0)
当然并不是每次为0的数据都需要处理
计算平均值等情况,nan是不参与计算的,但是0会
pandas 常用统计方法例:假设现在我们有一组从2006年到2016年1000部最流行的电影数据,我们想知道这些电影数据中评分的平均分,导演的人数等信息,我们应该怎么获取?
# coding=utf-8
import pandas as pd
import numpy as np
file_path = "IMDB-Movie-Data.csv"
df = pd.read_csv(file_path)
print(df.info())
print("***mean***"*50)
# print(df.head(1))
# 获取平均分
print(df["Rating"].mean())
print("***Director***"*50)
# 导演人数
#print(len(set(df["Director"].tolist())))
print(len(df["Director"].unique()))
print("***actors_num***"*50)
# 获取演员人数
temp_actors_list = df["Actors"].str.split(", ").tolist()
actors_list = [i for j in temp_actors_list for i in j]
actors_num = len(set(actors_list))
print(actors_num)
结果为:
RangeIndex: 1000 entries, 0 to 999 Data columns (total 12 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Rank 1000 non-null int64 1 Title 1000 non-null object 2 Genre 1000 non-null object 3 Description 1000 non-null object 4 Director 1000 non-null object 5 Actors 1000 non-null object 6 Year 1000 non-null int64 7 Runtime (Minutes) 1000 non-null int64 8 Rating 1000 non-null float64 9 Votes 1000 non-null int64 10 Revenue (Millions) 872 non-null float64 11 metascore 936 non-null float64 dtypes: float64(3), int64(4), object(5) memory usage: 74.3+ KB None 6.723199999999999 644 2015 Process finished with exit code 0
- 对于这一组电影数据,如果我们想rating,runtime的分布情况,应该如何呈现数据?
import numpy as np
from matplotlib import pyplot as plt
runtime_data = np.array([8.1, 7.0, 7.3, 7.2, 6.2, 6.1, 8.3, 6.4, 7.1, 7.0, 7.5, 7.8, 7.9, 7.7, 6.4, 6.6, 8.2, 6.7, 8.1, 8.0, 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.8, 6.3, 6.4, 7.1, 7.1, 6.8, 7.3, 6.7, 7.8, 6.3, 7.5, 6.8, 7.4, 6.8, 7.1, 7.6, 5.9, 6.6, 7.5, 6.4, 7.8, 7.2, 8.4, 6.2, 7.1, 6.3, 6.5, 6.9, 6.9, 6.6, 6.9, 7.7, 2.7, 5.4, 7.0, 6.6, 7.0, 6.9, 7.3, 5.8, 5.8, 6.9, 7.5, 6.3, 6.9, 6.1, 7.5, 6.8, 6.5, 5.5, 7.7, 3.5, 6.2, 7.1, 5.5, 7.1, 7.1, 7.1, 7.9, 6.5, 5.5, 6.5, 5.6, 6.8, 7.9, 6.2, 6.2, 6.7, 6.9, 6.5, 6.6, 6.4, 4.7, 7.2, 7.2, 6.7, 7.5, 6.6, 6.7, 7.5, 6.1, 6.4, 6.3, 6.4, 6.8, 6.1, 4.9, 7.3, 5.9, 6.1, 7.1, 5.9, 6.8, 5.4, 6.3, 6.2, 6.6, 4.4, 6.8, 7.3, 7.4, 6.1, 4.9, 5.8, 6.1, 6.4, 6.9, 7.2, 5.6, 4.9, 6.1, 7.8, 7.3, 4.3, 7.2, 6.4, 6.2, 5.2, 7.7, 6.2, 7.8, 7.0, 5.9, 6.7, 6.3, 6.9, 7.0, 6.7, 7.3, 3.5, 6.5, 4.8, 6.9, 5.9, 6.2, 7.4, 6.0, 6.2, 5.0, 7.0, 7.6, 7.0, 5.3, 7.4, 6.5, 6.8, 5.6, 5.9, 6.3, 7.1, 7.5, 6.6, 8.5, 6.3, 5.9, 6.7, 6.2, 5.5, 6.2, 5.6, 5.3])
max_runtime = runtime_data.max()
min_runtime = runtime_data.min()
print(min_runtime,max_runtime)
#设置不等宽的组距,hist方法中取到的会是一个左闭右开的去见[1.9,3.5)
num_bin_list = [1.9,3.5]
i=3.5
while i<=max_runtime:
i += 0.5
num_bin_list.append(i)
print(num_bin_list)
#设置图形的大小
plt.figure(figsize=(20,8),dpi=80)
plt.hist(runtime_data,num_bin_list)
#xticks让之前的组距能够对应上
plt.xticks(num_bin_list)
plt.show()



