这是油管上的一个帅哥的网课地址以下 https://www.youtube.com/watch?v=yzIMircGU5I&list=PL5-da3qGB5ICCsgW1MxlZ0Hq8LL5U3u9yhtml
# 传统方式
import pandas as pd
# 直接从URL中读取Chipotle订单的数据集,并将结果存储在数据库中
url1 = "https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/chipotle.tsv"
#定义地址
orders =pd.read_table(url1)#使用read_table()打开
# 检查前5行
orders.head()
Documentation for read_table
python
# 读取电影评论员的数据集(修改read_table的默认参数值)
user_cols = ['user_id','age','gender','occupation','zipcode']#定义列名
url2 = "https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/u.user"
#定义地址
#users=pd.read_table(url2,sep='|',header=None,names= user_clos,skiprows=2,skipfooter=3)
users = pd.read_table('http://bit.ly/movieusers', sep='|', header=None, names=user_cols)
#加入参数sep 分隔符,header 头部 标题,names 列名
# 检查前5行
users.head()
[Back to top]git
# 将UFO报告的数据集读入DataFrame
url3 = "https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/ufo.csv"#定义列名
ufo = pd.read_table(url3, sep=',')
# #用read_table打开csv文件,区别是 read_csv直接是用逗号隔开
ufo = pd.read_csv(url3)
# 检查前5行
ufo.head()
# #用括号法查看Series
ufo['City']
# #用点法查看Series,要注意 名字里面有空格或者是python专有字符的时候不能用,可是方便输入
ufo.City
括号表示法老是有效,而点表示法有局限性:github
# #这里的拼接也不能用点的方法
ufo['Location'] = ufo.City + ', ' + ufo.State
ufo.head()
[Back to top]正则表达式
# 将顶级IMDb电影的数据集读入DataFrame
url4="https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/imdb_1000.csv"
movies = pd.read_csv(url4)
#方法以括号结尾,而属性则没有:数据库
# 示例方法:显示前5行
movies.head()
#示例方法:计算摘要统计信息
movies.describe()
movies.describe(include=['object'])
# 示例属性:行数和列数
movies.shape
# 示例属性:每列的数据类型
movies.dtypes
# 使用describe方法的可选参数来仅汇总'object'列
movies.describe(include=['object'])
Documentation for describe
api
[Back to top]app
# 检查列名称
ufo.columns
# 使用'rename'方法重命名其中两列
ufo.rename(columns={'Colors Reported':'Colors_Reported', 'Shape Reported':'Shape_Reported'}, inplace=True)
ufo.columns
Documentation for rename
ide
# 经过覆盖'columns'属性替换全部列名
ufo = pd.read_table(url3, sep=',')
ufo_cols = ['city', 'colors reported', 'shape reported', 'state', 'time']
ufo.columns = ufo_cols
ufo.columns
# 使用'names'参数替换文件读取过程当中的列名
ufo = pd.read_csv(url3, header=0, names=ufo_cols)
ufo.columns
Documentation for read_csv
函数
ufo.columns = ufo.columns.str.replace(' ', '_') #如何批量修改替换使得列名无空格
ufo.columns
Documentation for str.replace
ufo = pd.read_table(url3, sep=',')
ufo.head()
# #axis=1 是纵向,inplace = True:不建立新的对象,直接对原始对象进行修改;
ufo.drop('Colors Reported', axis=1, inplace=True)
ufo.head()
Documentation for drop
# 一次删除多个列
ufo.drop(['City', 'State'], axis=1, inplace=True)
ufo.head()
# 一次删除多行(axis = 0表示行)
ufo.drop([0, 1], axis=0, inplace=True)
ufo.head()
#删除4行 按标签,axis=0 是横向,默认为横向,但建议写出来
movies.head()
#注意:如下任何排序方法都不会影响基础数据。 (换句话说,排序是暂时的)。
#排序单个Series
movies.title.sort_values().head()
# #排序单个Series 倒序
movies.title.sort_values(ascending=False).head()
Documentation for sort_values
for a Series. (Prior to version 0.17, use order
instead.)
# #以单个Series排序DataFrame
movies.sort_values('title').head()
# 改成按降序排序
movies.sort_values('title', ascending=False).head()
Documentation for sort_values
for a DataFrame. (Prior to version 0.17, use sort
instead.)
# 首先按'content_rating',而后按duration'排序DataFrame
movies.sort_values(['content_rating', 'duration']).head()
Summary of changes to the sorting API in pandas 0.17
movies.head()
# 检查行数和列数
movies.shape
##目标:过滤DataFrame行,仅显示“持续时间”至少为200分钟的电影
#
#先展现一个比较复杂的方法,用一个for循环制造一个和原数据同样行数,判断每一行是否符合条件,列表元素均为boolean
#建立一个列表,其中每一个元素引用一个DataFrame行:若是行知足条件,则返回true,不然返回False
booleans = []
for length in movies.duration:
if length >= 200:
booleans.append(True)
else:
booleans.append(False)
# 确认列表与DataFrame的长度相同
len(booleans)
# 检查前五个列表元素
booleans[0:5]
# 将列表转换为Series
is_long = pd.Series(booleans)
is_long.head()
# 使用带有布尔Series的括号表示法告诉DataFrame movies[is_long]要显示哪些行
movies[is_long]
# 简化上面的步骤:不须要编写for循环来建立is_long'
is_long = movies.duration >= 200
movies[is_long]#运用这种写法,pandas就知道,按照这个series去筛选
# 或等效地,将其写在一行(无需建立'is_long'对象)
movies[movies.duration >= 200]
# 从过滤后的DataFrame中选择“流派”系列
movies[movies.duration >= 200].genre
# 或者等效地,使用'loc'方法
movies.loc[movies.duration >= 200, 'genre']
Documentation for loc
# read a dataset of top-rated IMDb movies into a DataFrame
movies = pd.read_csv('http://bit.ly/imdbratings')
movies.head()
# 过滤DataFrame仅显示“持续时间”至少为200分钟的电影
movies[movies.duration >= 200]
理解逻辑运算符:
and
:仅当运算符的两边都为True时才为真or
:若是运算符的任何一侧为True,则为真
print(True and True)
print(True and False)
print(False and False)
print(True or True)
print(True or False)
print(False or False)
在pandas中指定多个过滤条件的规则:
使用&而不是和 使用|而不是或 在每一个条件周围添加括号以指定评估顺序
Goal: Further filter the DataFrame of long movies (duration >= 200) to only show movies which also have a 'genre' of 'Drama'
# 使用'&'运算符指定两个条件都是必需的
movies[(movies.duration >=200) & (movies.genre == 'Drama')]
# I不正确:使用'|'运算符会展现长或戏剧的电影
movies[(movies.duration >=200) | (movies.genre == 'Drama')].head()
##过滤原始数据框以显示“类型”为“犯罪”或“戏剧”或“动做”的电影
# 使用'|'运算符指定行能够匹配三个条件中的任何一个
movies[(movies.genre == 'Crime') | (movies.genre == 'Drama') | (movies.genre == 'Action')].head(10)
# 用isin等效
movies[movies.genre.isin(['Crime', 'Drama', 'Action'])].head(10)
Documentation for isin
Question: When reading from a file, how do I read in only a subset of the columns?
url3 = "https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/ufo.csv"#定义列名
ufo = pd.read_csv(url3)#用read_csv打开csv文件
ufo.columns
# 列名筛选
ufo = pd.read_csv(url3, usecols=['City', 'State'])
# 用位置切片等效
ufo = pd.read_csv(url3, usecols=[0, 4])
ufo.columns
Question: When reading from a file, how do I read in only a subset of the rows?
# 读3行数据
ufo = pd.read_csv(url3, nrows=3)
ufo
Documentation for read_csv
Question: How do I iterate through a Series?
# Series可直接迭代(如列表)
for c in ufo.City:
print(c)
Question: How do I iterate through a DataFrame?
# 可使用各类方法迭代DataFrame
for index, row in ufo.iterrows():
print(index, row.City, row.State)
Documentation for iterrows
Question: How do I drop all non-numeric columns from a DataFrame?
# 将酒精消耗数据集读入DataFrame,并检查数据类型
url7= 'https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/drinks.csv'
drinks = pd.read_csv(url7)
drinks.dtypes
# 仅包含DataFrame中的数字列
import numpy as np
drinks.select_dtypes(include=[np.number]).dtypes
Documentation for select_dtypes
Question: How do I know whether I should pass an argument as a string or a list?
# 描述全部数字列
drinks.describe()
# 传递字符串'all'来描述全部列
drinks.describe(include='all')
# 传递数据类型列表以仅描述多个类型
drinks.describe(include=['object', 'float64'])
# 即便您只想描述单个数据类型,也要传递一个列表
drinks.describe(include=['object'])
Documentation for describe
url7= 'https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/drinks.csv'
drinks = pd.read_csv(url7)
drinks.head()
# drop a column (temporarily)
drinks.drop('continent', axis=1).head()
Documentation for drop
# 删除一列(暂时)
drinks.drop(2, axis=0).head()
使用axis参数引用行或列时:
axis 0表示行 axis 1指的是列
# 计算每一个数字列的平均值
drinks.mean()
# 或等效地,明确指定轴
drinks.mean(axis=0)
Documentation for mean
# 计算每一行的平均值
drinks.mean(axis=1).head()
使用axis参数执行数学运算时:
# 'index' 等效 axis 0
drinks.mean(axis='index')
# 'columns' 等效 axis 1
drinks.mean(axis='columns').head()
url1 = "https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/chipotle.tsv"
#定义地址
orders =pd.read_table(url1)#使用read_table()打开
orders.head()
# 在Python中访问字符串方法的经常使用方法
'hello'.upper()
# spandas Series 的字符串方法经过'str'访问
orders.item_name.str.upper().head()
# string方法'contains'检查子字符串并返回一个布尔Series
orders.item_name.str.contains('Chicken').head()
# 布尔Series筛选DataFrame
orders[orders.item_name.str.contains('Chicken')].head()
# 字符串方法能够连接在一块儿
orders.choice_description.str.replace('[', '').str.replace(']', '').head()
# 许多pandas字符串方法支持正则表达式
orders.choice_description.str.replace('[\[\]]', '').head()
String handling section of the pandas API reference
url7= 'https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/drinks.csv'
drinks = pd.read_csv(url7)
drinks.head()
# 检查每一个系列的数据类型
drinks.dtypes
# 更改现有系列的数据类型
drinks['beer_servings'] = drinks.beer_servings.astype(float)
drinks.dtypes
Documentation for astype
# 或者,在读取文件时更改系列的数据类型
drinks = pd.read_csv(url7, dtype={'beer_servings':float})
drinks.dtypes
orders = pd.read_table(url1)
orders.head()
# 检查每一个系列的数据类型
orders.dtypes
# 将字符串转换为数字以进行数学运算
orders.item_price.str.replace('$', '').astype(float).mean()
# 字符串方法'contains'检查子字符串并返回一个布尔系列
orders.item_name.str.contains('Chicken').head()
# 将布尔系列转换为整数(False = 0,True = 1)
orders.item_name.str.contains('Chicken').astype(int).head()
drinks = pd.read_csv(url7)
drinks.head()
# 计算整个数据集中的平均beer_servings
drinks.beer_servings.mean()
# 计算非洲国家的平均beer_servings
drinks[drinks.continent=='Africa'].beer_servings.mean()
#计算每一个大陆的平均beer_servings
drinks.groupby('continent').beer_servings.mean()
Documentation for groupby
# 其余聚合函数(例如'max')也能够与groupby一块儿使用
drinks.groupby('continent').beer_servings.max()
# 多个聚合函数能够同时应用
drinks.groupby('continent').beer_servings.agg(['count', 'mean', 'min', 'max'])
Documentation for agg
# 不指定列,就会算出全部数值列
drinks.groupby('continent').mean()
# 容许绘图出如今jupyter notebook中
%matplotlib inline
# 直接在上面的DataFrame的并排条形图
drinks.groupby('continent').mean().plot(kind='bar')
Documentation for plot
# read a dataset of top-rated IMDb movies into a DataFrame
url4="https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/imdb_1000.csv"
movies = pd.read_csv(url4)
movies.head()
# 检查数据类型
movies.dtypes
探索非数字系列
# 计算最多见值的非空值,惟一值和频率
movies.genre.describe()
Documentation for describe
# 数Series中每一个值发生的次数
movies.genre.value_counts()
Documentation for value_counts
# 显示百分比而不是原始计数
movies.genre.value_counts(normalize=True)
# '输出的是一个Series
type(movies.genre.value_counts())
# 可使用Series方法
movies.genre.value_counts().head()
# 显示Series中惟一值
movies.genre.unique()
#数Series中惟一值的数量
movies.genre.nunique()
# 两个Series的交叉列表
pd.crosstab(movies.genre, movies.content_rating)
Documentation for crosstab
探索数字系列:
# 计算各类汇总统计
movies.duration.describe()
# 许多统计数据都是做为Series方法实现的
movies.duration.mean()
Documentation for mean
# 'value_counts' 主要用于分类数据,而不是数字数据
movies.duration.value_counts().head()
# 容许绘图出如今jupyter notebook中
%matplotlib inline
# 'duration'Series的直方图(显示数值变量的分布)
movies.duration.plot(kind='hist')
# 'genre'Series'value_counts'的条形图
movies.genre.value_counts().plot(kind='bar')
Documentation for plot
原文出处:https://www.cnblogs.com/romannista/p/10659805.html