萌新向Python数据分析及数据挖掘 第二章 pandas 第一节 pandas使用基础Q&A 16-30
16. How do I handle missing values in pandas? (video)
url3 = "https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/ufo.csv"#定义列名
ufo = pd.read_csv(url3)#用read_csv打开csv文件
ufo.tail()
“NaN”是什么意思?
“NaN”不是字符串,而是一个特殊值:numpy.nan。 它代表“非数字”并表示缺失值。 read_csv在读取文件时检测缺失值(默认情况下),并用此特殊值替换它们。
Documentation for read_csv
# ''isnull'返回一个布尔DataFrame(如果缺少则为True,如果没有缺失则为False)
ufo.isnull().tail()
# 'nonnull'返回'isnull'的反面(如果不丢失,则返回true,如果丢失则返回False)
ufo.notnull().tail()
# 计算每个Series中缺失值的数量
ufo.isnull().sum()
此计算有效,因为:
1.默认情况下,DataFrame的sum
**方法在axis = 0
上运行(因此产生列总和)。 2.为了添加布尔值,pandas将“True”转换为 1 ,将“False”转换为 0 **。
# 使用'isnull'Series方法过滤DataFrame行
ufo[ufo.City.isnull()].head()
How to handle missing values depends on the dataset as well as the nature of your analysis. Here are some options:
# 检查行数和列数
ufo.shape
# 如果连续缺少“任何”值,则删除该行
ufo.dropna(how='any').shape
Documentation for dropna
# 默认情况下,'dropna'的inplace'参数为False,因此只暂时删除行
ufo.shape
# 如果一行中缺少'all'值,则删除该行(在这种情况下不丢弃)
ufo.dropna(how='all').shape
# 给 any 一个范围
ufo.dropna(subset=['City', 'Shape Reported'], how='any').shape
# 给all 一个范围
ufo.dropna(subset=['City', 'Shape Reported'], how='all').shape
# 默认情况下,value_counts'不包含缺失值
ufo['Shape Reported'].value_counts().head()
# 明确包含缺失值
ufo['Shape Reported'].value_counts(dropna=False).head()
Documentation for value_counts
# 使用指定值填充缺失值
ufo['Shape Reported'].fillna(value='VARIOUS', inplace=True)
Documentation for fillna
# 确认填写了缺失值
ufo['Shape Reported'].value_counts().head()
17. What do I need to know about the pandas index? (Part 1) (video)
drinks = pd.read_csv(url7)
drinks.head()
# 每个DataFrame都有一个索引(有时称为“行标签”)
drinks.index
# 列名也存储在特殊的“索引”对象中
drinks.columns
# 索引和列名都不包含在形状中
drinks.shape
# 如果不定义索引和列名,则默认为整数
pd.read_table('http://bit.ly/movieusers', header=None, sep='|').head()
索引用于什么?
识别 选择 对齐
# i识别:过滤DataFrame时,每行保留索引
drinks[drinks.continent=='South America']
# 选择:使用索引选择DataFrame的一部分
drinks.loc[23, 'beer_servings']
Documentation for loc
# 将现有列设置为索引
drinks.set_index('country', inplace=True)
drinks.head()
Documentation for set_index
# 'country'现在是索引
drinks.index
# 'country'不再是列名
drinks.columns
# 'country'数据不再是DataFrame内容的一部分
drinks.shape
# 国家名字现在可用于选择
drinks.loc['Brazil', 'beer_servings']
# 索引名称是可选的
drinks.index.name = None
drinks.head()
# 恢复索引名称,并将索引移回列
drinks.index.name = 'country'
drinks.reset_index(inplace=True)
drinks.head()
Documentation for reset_index
# 许多DataFrame方法输出一个DataFrame
drinks.describe()
# 您可以使用其索引和列与任何DataFrame进行交互
drinks.describe().loc['25%', 'beer_servings']
18. What do I need to know about the pandas index? (Part 2) (video)
drinks = pd.read_csv(url7)
drinks.head()
# 每个DataFrame都有一个索引
drinks.index
# 每个Series还有一个索引(从DataFrame继承)
drinks.continent.head()
# 将'country'设置为索引
drinks.set_index('country', inplace=True)
Documentation for set_index
# Series 索引在左侧,值在右侧
drinks.continent.head()
# 系Series的另一个例子(来自'value_counts'方法的输出)
drinks.continent.value_counts()
Documentation for value_counts
# Series 访问索引
drinks.continent.value_counts().index
# 访问Series 的值
drinks.continent.value_counts().values
#可以通过索引选择系列中的元素(使用括号表示法)
drinks.continent.value_counts()['Africa']
# 任何Series都可以按其值排序
drinks.continent.value_counts().sort_values()
# a任何Series都可以按其索引排序
drinks.continent.value_counts().sort_index()
Documentation for sort_values
and sort_index
索引用于什么?
识别 选择 对齐
# beer_servings'包含每人平均每年的啤酒摄取量
drinks.beer_servings.head()
# 创建一个包含两个国家人口的Series
people = pd.Series([3000000, 85000], index=['Albania', 'Andorra'], name='population')
people
Documentation for Series
# 计算每个国家的年度啤酒总量
(drinks.beer_servings * people).head()
两个Series按其指数对齐。 如果任一Series中缺少值,则结果标记为NaN。 对齐使我们能够轻松处理不完整的数据。
# concatenate the 'drinks' DataFrame with the 'population' Series (aligns by the index)
pd.concat([drinks, people], axis=1).head()
19. How do I select multiple rows and columns from a pandas DataFrame? (video)
ufo = pd.read_csv(url3)
ufo.head(3)
The loc
y loc方法用于按标签选择行和列。你可以传递它:
单个标签 标签列表 标签切片 布尔Series 冒号(表示“所有标签”)
# 第0行,所有列
ufo.loc[0, :]
# 头三行,所有列
ufo.loc[[0, 1, 2], :]
# 0:2行 包括2, all columns
ufo.loc[0:2, :]
# t这意味着“所有列”,但明确声明“所有列”更好
ufo.loc[0:2]
# 行0到行2(包含行2),列'城市'
ufo.loc[0:2, 'City']
# 行0到行2(包含行2), 列 'City' and 'State'
ufo.loc[0:2, ['City', 'State']]
# 使用双括号完成相同的事情 - 但使用'loc'是首选,因为它更明确
ufo[['City', 'State']].head(3)
# 行0到行2(包含行2), 列 'City' 到 'State')
ufo.loc[0:2, 'City':'State']
# 使用'head'和'drop'完成同样的事情
ufo.head(3).drop('Time', axis=1)
# 'City'为'Oakland'的行,'State'列
ufo.loc[ufo.City=='Oakland', 'State']
# 使用“链式索引”完成同样的事情 - 但使用'loc'是首选,因为链式索引可能会导致问题
ufo[ufo.City=='Oakland'].State
The iloc
iloc'方法用于通过整数位置选择行和列。你可以传递它:
- 单个整数位置
- 整数位置列表
- 整数位置切片
- 冒号(表示“所有整数位置”)
# 位置0和1中的行,位置0和3中的列
ufo.iloc[[0, 1], [0, 3]]
# 位置0到2中的行(不包括),位置0到4中的列(不包括)
ufo.iloc[0:2, 0:4]
# 所有列中位置0到2(不包括)的行
ufo.iloc[0:2, :]
# 完成同样的事情 - 但使用'iloc'是首选,因为它更明确
ufo[0:2]
The ix
ix
方法用于通过标签或整数位置选择行和列,并且只应在需要在同一调用中混合基于标签和基于整数的选择时使用。
# read a dataset of alcohol consumption into a DataFrame and set 'country' as the index
drinks = pd.read_csv(url7, index_col='country')
drinks.head()
# 标有'Albania'的行,位于0的列
drinks.ix['Albania', 0]
# row in position 1, column with label 'beer_servings'
drinks.ix[1, 'beer_servings']
使用带有ix
的数字的规则:
- 如果索引是字符串,则数字被视为整数位置,因此切片在右侧是不包含。
- 如果索引是整数,则数字被视为标签,因此切片是包含。
# 行'阿尔巴尼亚'到'安道尔'(包括),0到2位的列(包含)
drinks.ix['Albania':'Andorra', 0:2]
# 行0到2(含),0到2位的列(不包括)
ufo.ix[0:2, 0:2]
20. When should I use the "inplace" parameter in pandas? (video)
# read a dataset of UFO reports into a DataFrame
ufo = pd.read_csv(url3)
ufo.head()
ufo.shape
# 删除“城市”列(因为inplace = False,不会影响DataFrame)
ufo.drop('City', axis=1).head()
# 确认实际上没有删除“城市”列
ufo.head()
# 删除“城市”列(因为inplace = True,确实会影响DataFrame)
ufo.drop('City', axis=1, inplace=True)
# 确认实际删除了“城市”列
ufo.head()
# 如果该行中缺少任何值,则删除一行(因为inplace = False,不会影响DataFrame)
ufo.dropna(how='any').shape
# 确认没有实际删除任何行
ufo.shape
# 使用赋值语句而不是'inplace'参数
ufo = ufo.set_index('Time')
ufo.tail()
# 使用“向后填充”策略填充缺失值(因为inplace = False不影响DataFrame)
ufo.fillna(method='bfill').tail()
# 使用“前向填充”策略进行操作(因为inplace = False,不会影响DataFrame)
ufo.fillna(method='ffill').tail()
21. How do I make my pandas DataFrame smaller and faster? (video)
drinks = pd.read_csv(url7)
drinks.head()
# 确切的内存使用是未知的,因为对象列是别处的引用
drinks.info()
#强制pandas计算真正的内存使用量
drinks.info(memory_usage='deep')
# 计算每个系列的内存使用量(以字节为单位)
drinks.memory_usage(deep=True)
Documentation for info
and memory_usage
# 使用'category'数据类型(pandas 0.15)将'continent'字符串存储为整数
drinks['continent'] = drinks.continent.astype('category')
drinks.dtypes
# 'continent'系列似乎没有变化
drinks.continent.head()
# strings are now encoded (0 means 'Africa', 1 means 'Asia', 2 means 'Europe', etc.)
drinks.continent.cat.codes.head()
# 现在对编码进行编码(0表示'非洲',1表示'亚洲',2表示'欧洲'等)
drinks.memory_usage(deep=True)
# country' Series中重复这个过程'
drinks['country'] = drinks.country.astype('category')
drinks.memory_usage(deep=True)
# 因为我们创建了193个类别,因此内存使用增加
drinks.country.cat.categories
类别数据类型只应与具有少量可能值的字符串Series一起使用。
# 从字典中创建一个小型DataFrame
df = pd.DataFrame({'ID':[100, 101, 102, 103], 'quality':['good', 'very good', 'good', 'excellent']})
df
# 按“质量”系列排序DataFrame(按字母顺序排列)
df.sort_values('quality')
# 定义类别的逻辑顺序
df['quality'] = df.quality.astype('category', categories=['good', 'very good', 'excellent'], ordered=True)
df.quality
# 按“质量”系列(逻辑顺序)输出DataFrame)
df.sort_values('quality')
# 比较运算符使用有序类别
df.loc[df.quality > 'good', :]
22. How do I use pandas with scikit-learn to create Kaggle submissions? (video)
# 从Kaggle的泰坦尼克号竞赛中将训练数据集读入DataFrame
url5 = 'https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/titanic_train.csv'
train = pd.read_csv(url5)
train.head()
Goal: Predict passenger survival aboard the Titanic based on passenger attributes
#根据乘客属性预测泰坦尼克号上的乘客生存率
# 通过选择两个DataFrame列来创建特征矩阵“X”
feature_cols = ['Pclass', 'Parch']
X = train.loc[:, feature_cols]
X.shape
# 通过选择一个系列来创建一个响应向量'y'
y = train.Survived
y.shape
Note: There is no need to convert these pandas objects to NumPy arrays. scikit-learn will understand these objects as long as they are entirely numeric and the proper shapes.
#无需将这些pandas对象转换为NumPy数组。 scikit-learn将理解这些对象,只要它们完全是数字和正确的形状
# 将分类模型拟合到训练数据中
from sklearn.linear_model import LogisticRegression
logreg = LogisticRegression()
logreg.fit(X, y)
Video series: Introduction to machine learning with scikit-learn
# 从Kaggle的泰坦尼克号竞赛中读取测试数据集到DataFrame
url6 ="https://raw.githubusercontent.com/justmarkham/pandas-videos/master/data/titanic_test.csv"
test = pd.read_csv(url6)
test.head()
# 根据与训练数据匹配的测试数据创建特征矩阵
X_new = test.loc[:, feature_cols]
X_new.shape
# 使用拟合模型对测试集进行预测
new_pred_class = logreg.predict(X_new)
# 输出结果
pd.DataFrame({'PassengerId':test.PassengerId, 'Survived':new_pred_class}).head()
Documentation for the DataFrame
constructor
# 通过将PassengerID设置为索引来确保PassengerID是第一列
pd.DataFrame({'PassengerId':test.PassengerId, 'Survived':new_pred_class}).set_index('PassengerId').head()
# 将DataFrame写入可以提交给Kaggle的CSV文件
pd.DataFrame({'PassengerId':test.PassengerId, 'Survived':new_pred_class}).set_index('PassengerId').to_csv('sub.csv')
Documentation for to_csv
# save a DataFrame to disk ("pickle it")
train.to_pickle('train.pkl')
# read a pickled object from disk ("unpickle it")
pd.read_pickle('train.pkl').head()
Documentation for to_pickle
and read_pickle
23. More of your pandas questions answered! (video)
Question: Could you explain how to read the pandas documentation?
Question: What is the difference between ufo.isnull()
and pd.isnull(ufo)
?
ufo = pd.read_csv(url3)
ufo.head()
# #使用'isnull'作为顶层函数
pd.isnull(ufo).head()
# 等效:使用'isnull'作为DataFrame方法
ufo.isnull().head()
Documentation for isnull
Question: Why are DataFrame slices inclusive when using .loc
, but exclusive when using .iloc
?
# 基于标签的切片包括开始和结束
ufo.loc[0:4, :]
# 基于位置的切片包括开始和不包括结束
ufo.iloc[0:4, :]
# iloc'只是遵循NumPy的切片惯例......
ufo.values[0:4, :]
# ..而NumPy只是遵循Python的切片约定
'python'[0:4]
# oc'包含停止标签,因为您不一定知道它后面会是什么标签
ufo.loc[0:4, 'City':'State']
Question: How do I randomly sample rows from a DataFrame?
# 随机取三行
ufo.sample(n=3)
Documentation for sample
# 使用'random_state'参数进行使结果可以再现
ufo.sample(n=3, random_state=42)
# 按比例采样
train = ufo.sample(frac=0.75, random_state=99)
# 剩下数据存到另一个DataFrame
test = ufo.loc[~ufo.index.isin(train.index), :]
Documentation for isin
24. How do I create dummy variables in pandas? (video)
train = pd.read_csv(url5)
train.head()
# 使用'map'方法创建'Sex_male'虚拟变量
train['Sex_male'] = train.Sex.map({'female':0, 'male':1})
train.head()
Documentation for map
# 替代方法:使用'get_dummies'为每个可能的值创建一列
pd.get_dummies(train.Sex).head()
Generally speaking:
- If you have "K" possible values for a categorical feature, you only need "K-1" dummy variablesto capture all of the information about that feature.
- One convention is to drop the first dummy variable, which defines that level as the "baseline".
"""一般来说:
如果分类特征具有“K”个可能值,则只需要“K-1”虚拟变量来捕获有关该特征的所有信息。
一种惯用方法是删除第一个虚拟变量,该变量将该级别定义为“基线”。"""
# 使用'iloc'方法删除第一个虚拟变量('female')
pd.get_dummies(train.Sex).iloc[:, 1:].head()
# 添加前缀以标识虚拟变量的来源
pd.get_dummies(train.Sex, prefix='Sex').iloc[:, 1:].head()
# 使用 'get_dummies' 处理具有3个可能值
pd.get_dummies(train.Embarked, prefix='Embarked').head(10)
# 删除第一个虚拟变量('C')
pd.get_dummies(train.Embarked, prefix='Embarked').iloc[:, 1:].head(10)
How to translate these values back to the original 'Embarked' value:
- 0, 0 means C
- 1, 0 means Q
- 0, 1 means S
# 保存虚拟变量的DataFrame并将它们连接到原始DataFram
embarked_dummies = pd.get_dummies(train.Embarked, prefix='Embarked').iloc[:, 1:]
train = pd.concat([train, embarked_dummies], axis=1)
train.head()
Documentation for concat
# 重新读取DataFrame
train = pd.read_csv(url5)
train.head()
# 将DataFrame传递给'get_dummies'并指定哪些列为dummy(它删除了原始列)
pd.get_dummies(train, columns=['Sex', 'Embarked']).head()
# 使用'drop_first'参数(pandas 0.18)删除每个特征的第一个虚拟变量
pd.get_dummies(train, columns=['Sex', 'Embarked'], drop_first=True).head()
Documentation for get_dummies
25. How do I work with dates and times in pandas? (video)
ufo = pd.read_csv(url3)
ufo.head()
# 'Time'当前存储为字符串
ufo.dtypes
# 可以使用字符串切片访问小时,但这种方法很容易出问题
ufo.Time.str.slice(-5, -3).astype(int).head()
# 将“时间”转换为日期时间格式
ufo['Time'] = pd.to_datetime(ufo.Time)
ufo.head()
ufo.dtypes
Documentation for to_datetime
#使用Series方法
ufo.Time.dt.hour.head()
ufo.Time.dt.weekday_name.head()
ufo.Time.dt.dayofyear.head()
API reference for datetime properties and methods
# convert a single string to datetime format (outputs a timestamp object)
ts = pd.to_datetime('1/1/1999')
ts
# 将datetime系列与时间戳进行比较
ufo.loc[ufo.Time >= ts, :].head()
# 使用时间戳执行数学运算(输出timedelta对象)
ufo.Time.max() - ufo.Time.min()
# timedelta对象还具有您可以访问的属性
(ufo.Time.max() - ufo.Time.min()).days
# 允许绘图出现在笔记本jupyter notebook中
%matplotlib inline
# 计算每年不明飞行物报告的数量
ufo['Year'] = ufo.Time.dt.year
ufo.Year.value_counts().sort_index().head()
# 绘制每年不明飞行物报告的数量(默认折线图)
ufo.Year.value_counts().sort_index().plot()
26. How do I find and remove duplicate rows in pandas? (video)
user_cols = ['user_id', 'age', 'gender', 'occupation', 'zip_code']
users = pd.read_table(url2, sep='|', header=None, names=user_cols, index_col='user_id')
users.head()
users.shape
# 检测重复的邮政编码:如果项目与之前的项目相同,则为真
users.zip_code.duplicated().tail()
# 计算重复项(True变为1,False变为0)
users.zip_code.duplicated().sum()
# 检测重复的DataFrame行:如果整行与前一行相同,则为True
users.duplicated().tail()
# 数重复的行
users.duplicated().sum()
Logic for duplicated
:
keep='first'
(default): Mark duplicates as True except for the first occurrence.keep='last'
: Mark duplicates as True except for the last occurrence.keep=False
: Mark all duplicates as True.
"""duplicated的逻辑:
keep ='first'(默认值):将重复项标记为True,但第一次出现除外。
keep ='last':将重复项标记为True,但最后一次出现除外。
keep = False:将所有重复项标记为True。"""
# 检查重复行,忽略最第一次出现的
users.loc[users.duplicated(keep='first'), :]
# 检查重复行,忽略最后一个出现的
users.loc[users.duplicated(keep='last'), :]
# 检查重复行,保留所有重复数据
users.loc[users.duplicated(keep=False), :]
# 删除重复的行(默认情况下为inplace = False)
users.drop_duplicates(keep='first').shape
users.drop_duplicates(keep='last').shape
users.drop_duplicates(keep=False).shape
Documentation for drop_duplicates
# 在识别重复项时,只考虑列的子集
users.duplicated(subset=['age', 'zip_code']).sum()
users.drop_duplicates(subset=['age', 'zip_code']).shape
27. How do I avoid a SettingWithCopyWarning in pandas? (video)
movies = pd.read_csv(url4)
movies.head()
# 数'content_rating'系列中的缺失值
movies.content_rating.isnull().sum()
# 检查包含缺少值的DataFrame行
movies[movies.content_rating.isnull()]
# 检查'content_rating'系列中的唯一值
movies.content_rating.value_counts()
Goal: Mark the 'NOT RATED' values as missing values, represented by 'NaN'.
#目标:将“未评级”值标记为缺失值,由“NaN”表示。
# 首先,找到相关的行
movies[movies.content_rating=='NOT RATED'].head()
# 然后,从这些行中选择'content_rating'系列
movies[movies.content_rating=='NOT RATED'].content_rating.head()
# 最后,用'NaN'(从NumPy导入)替换'NOT RATED'值
import numpy as np
movies[movies.content_rating=='NOT RATED'].content_rating = np.nan
Problem: That statement involves two operations, a __getitem__
and a __setitem__
. pandas can't guarantee whether the __getitem__
operation returns a view or a copy of the data.
- If
__getitem__
returns a view of the data,__setitem__
will affect the 'movies' DataFrame. - But if
__getitem__
returns a copy of the data,__setitem__
will not affect the 'movies' DataFrame.
"""问题:该语句涉及两个操作,__ getitem__和__setitem__。 pandas无法保证__getitem__操作是返回视图还是数据副本。
如果__getitem__返回数据视图,__ setitem__将影响'movies'DataFrame。
但是如果__getitem__返回数据的副本,__ setitem__将不会影响'movies'DataFrame。"""
# 'content_rating'系列没有改变
movies.content_rating.isnull().sum()
Solution: Use the loc
method, which replaces the 'NOT RATED' values in a single __setitem__
operation.
"""解决方案:使用loc方法,该方法用单个__setitem__操作中替换“NOT RATED”值。"""
# 用'NaN'替换'NOT RATED'值(不会导致SettingWithCopyWarning)
movies.loc[movies.content_rating=='NOT RATED', 'content_rating'] = np.nan
# 这一次,'content_rating'Sreies发生了变化
movies.content_rating.isnull().sum()
Summary: Use the loc
method any time you are selecting rows and columns in the same statement.
More information: Modern Pandas (Part 1)
# 创建一个仅包含高'star_rating'影片的DataFrame
top_movies = movies.loc[movies.star_rating >= 9, :]
top_movies
Goal: Fix the 'duration' for 'The Shawshank Redemption'.
'目标:修复“The Shawshank Redemption”的“持续时间”。'
# 用正确的持续时间覆盖相关的单元格
top_movies.loc[0, 'duration'] = 150
Problem: pandas isn't sure whether 'top_movies' is a view or a copy of 'movies'.
"问题:pandas不确定'top_movies'是视图还是'电影'的副本。"
# 结果还是修改了
top_movies
# 'movies' 电影的DataFrame没有改变
movies.head(1)
Solution: Any time you are attempting to create a DataFrame copy, use the copy
method.
"解决方案:每次尝试创建DataFrame副本时,请使用copy方法。"
# 明确创建'电影'的副本
top_movies = movies.loc[movies.star_rating >= 9, :].copy()
# andas现在知道你正在更新副本而不是视图(不会导致SettingWithCopyWarning
top_movies.loc[0, 'duration'] = 150
# 'top_movies'DataFrame已更新
top_movies
Documentation on indexing and selection: Returning a view versus a copy
Stack Overflow: What is the point of views in pandas if it is undefined whether an indexing operation returns a view or a copy?
28. How do I change display options in pandas? (video)
drinks = pd.read_csv(url7)
# 打印时仅显示60行
drinks
# 检查'max_rows'选项的当前设置
pd.get_option('display.max_rows')
Documentation for get_option
# 覆盖当前设置,以便显示所有行
pd.set_option('display.max_rows', None)
drinks
# 将'max_rows'选项重置为默认值
pd.reset_option('display.max_rows')
Documentation for set_option
and reset_option
# 'max_columns'选项类似于'max_rows'
pd.get_option('display.max_columns')
train = pd.read_csv(url5)
train.head()
# 由于“max_colwidth”选项,省略号显示在第1行的“名称”单元格中
pd.get_option('display.max_colwidth')
# 覆盖当前设置,以便显示更多字符
pd.set_option('display.max_colwidth', 1000)
train.head()
# 覆盖''precision' '设置以显示'票价'小数点后的2位数
pd.set_option('display.precision', 2)
train.head()
# 在饮料DataFrame中添加两个无意义的列
drinks['x'] = drinks.wine_servings * 1000
drinks['y'] = drinks.total_litres_of_pure_alcohol * 1000
drinks.head()
# 使用Python格式字符串将逗号指定为千位分隔符
pd.set_option('display.float_format', '{:,}'.format)
drinks.head()
# y'受影响(但不是'x')因为'float_format'选项只影响浮点数(不是整数)
drinks.dtypes
# 查看选项说明(包括默认值和当前值)
pd.describe_option()
# 按名称搜索特定选项
pd.describe_option('rows')
Documentation for describe_option
# 将所有选项重置为其默认值
pd.reset_option('all')
29. How do I create a pandas DataFrame from another object? (video)
# 从字典创建一个DataFrame(键成为列名,值成为数据)
pd.DataFrame({'id':[100, 101, 102], 'color':['red', 'blue', 'red']})
# 指定列的顺序并定义索引
df = pd.DataFrame({'id':[100, 101, 102], 'color':['red', 'blue', 'red']}, columns=['id', 'color'], index=['a', 'b', 'c'])
df
Documentation for DataFrame
# 从列表中的列表结构创建一个DataFrame(每个内部列表成为一行)
pd.DataFrame([[100, 'red'], [101, 'blue'], [102, 'red']], columns=['id', 'color'])
# 创建一个NumPy数组(形状为4乘2)并用0到1之间的随机数填充它
import numpy as np
arr = np.random.rand(4, 2)
arr
# 从NumPy数组创建一个DataFrame
pd.DataFrame(arr, columns=['one', 'two'])
# 创建学生ID(100到109)和测试分数(60到10之间的随机整数)的DataFrame
pd.DataFrame({'student':np.arange(100, 110, 1), 'test':np.random.randint(60, 101, 10)})
# set_index'可以与DataFrame构造函数链接以选择索引
pd.DataFrame({'student':np.arange(100, 110, 1), 'test':np.random.randint(60, 101, 10)}).set_index('student')
Documentation for set_index
# 使用Series构造函数创建一个新Series
s = pd.Series(['round', 'square'], index=['c', 'b'], name='shape')
s
Documentation for Series
# 连接DataFrame和Series(使用axis = 1来连接列)
pd.concat([df, s], axis=1)
Notes:
- The Series name became the column name in the DataFrame.
- The Series data was aligned to the DataFrame by its index.
- The 'shape' for row 'a' was marked as a missing value (NaN) because that index was not present in the Series.
Documentation for concat
"""笔记:
系列名称成为DataFrame中的列名称。
Series数据通过其索引与DataFrame对齐。
行'a'的'形状'被标记为缺失值(NaN),因为该索引在系列中不存在。"""
30. How do I apply a function to a pandas Series or DataFrame? (video)
# read the training dataset from Kaggle's Titanic competition into a DataFrame
train = pd.read_csv(url5)
train.head()
Goal: Map the existing values of a Series to a different set of values
Method: map
(Series method)
"""目标:将Series的现有值映射到不同的值集
方法:map(Series方法)"""
# map 'female' to 0 and 'male' to 1
train['Sex_num'] = train.Sex.map({'female':0, 'male':1})
train.loc[0:4, ['Sex', 'Sex_num']]
Goal: Apply a function to each element in a Series
Method: apply
(Series method)
Note: map
can be substituted for apply
in many cases, but apply
is more flexible and thus is recommended
"""目标:将函数应用于系列中的每个元素
方法:apply(Series方法)
注意:在许多情况下,map可以替换为apply,但是apply更灵活,因此建议使用"""
# 计算“姓名”系列中每个字符串的长度
train['Name_length'] = train.Name.apply(len)
train.loc[0:4, ['Name', 'Name_length']]
# 将“票价”系列中的每个元素四舍五入到下一个整数
import numpy as np
train['Fare_ceil'] = train.Fare.apply(np.ceil)
train.loc[0:4, ['Fare', 'Fare_ceil']]
# 我们想要提取每个人的姓氏
train.Name.head()
# 使用字符串方法以逗号分隔“名称”系列(返回一Series列表)
train.Name.str.split(',').head()
# 定义一个函数,该函数根据位置从列表中返回一个元素
def get_element(my_list, position):
return my_list[position]
# 应用'get_element'函数并将'position'作为关键字参数传递
train.Name.str.split(',').apply(get_element, position=0).head()
# 或者,使用lambda函数
train.Name.str.split(',').apply(lambda x: x[0]).head()
Goal: Apply a function along either axis of a DataFrame
Method: apply
(DataFrame method)
"""目标:沿DataFrame的任一轴应用函数
方法:apply(DataFrame方法)"""
drinks = pd.read_csv(url7)
drinks.head()
# 选择要使用的DataFrame的子集
drinks.loc[:, 'beer_servings':'wine_servings'].head()
# 沿axix 0应用'max'函数来计算每列中的最大值
drinks.loc[:, 'beer_servings':'wine_servings'].apply(max, axis=0)
# 沿axis 1应用'max'函数来计算每行的最大值
drinks.loc[:, 'beer_servings':'wine_servings'].apply(max, axis=1).head()
# 使用'np.argmax'计算哪一列具有每行的最大值
drinks.loc[:, 'beer_servings':'wine_servings'].apply(np.argmax, axis=1).head()
Goal: Apply a function to every element in a DataFrame
Method: applymap
(DataFrame method)
# 将每个DataFrame元素转换为float
drinks.loc[:, 'beer_servings':'wine_servings'].applymap(float).head()
#覆盖现有的DataFrame列
drinks.loc[:, 'beer_servings':'wine_servings'] = drinks.loc[:, 'beer_servings':'wine_servings'].applymap(float)
drinks.head()