Pandas是入门Python做数据分析所必须要掌握的一个库,本文精选了十套练习题,帮助读者上手Python代码,完成数据集探索。

本文内容由科赛网翻译整理自Github,建议读者完成科赛网 从零上手Python关键代码Pandas基础命令速查表 教程学习的之后,再对本教程代码进行调试学习。

【小提示:本文所使用的数据集下载地址:DATA | TRAIN 练习数据集

一两赘肉无:10套练习,教你如何用Pandas做数据分析【1-5】zhuanlan.zhihu.com10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图1

↓↓↓练习【6-10】↓↓↓

练习6-统计

探索风速数据

相应数据集:wind.data

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图2

步骤1 导入必要的库

  1. # 运行以下代码
  2. import pandas as pd
  3. import datetime

步骤2 从以下地址导入数据

  1. import pandas as pd
  2. # 运行以下代码
  3. path6 = "../input/pandas_exercise/exercise_data/wind.data" # wind.data

步骤3 将数据作存储并且设置前三列为合适的索引

  1. import datetime
  2. # 运行以下代码
  3. data = pd.read_table(path6, sep = "\s+", parse_dates = [[0,1,2]])
  4. data.head()

out[293]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图3

步骤4 2061年?我们真的有这一年的数据?创建一个函数并用它去修复这个bug

  1. # 运行以下代码
  2. def fix_century(x):
  3. year = x.year - 100 if x.year > 1989 else x.year
  4. return datetime.date(year, x.month, x.day)
  5. # apply the function fix_century on the column and replace the values to the right ones
  6. data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
  7. # data.info()
  8. data.head()

out[294]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图4

步骤5 将日期设为索引,注意数据类型,应该是datetime64[ns]

  1. # 运行以下代码
  2. # transform Yr_Mo_Dy it to date type datetime64
  3. data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
  4. # set 'Yr_Mo_Dy' as the index
  5. data = data.set_index('Yr_Mo_Dy')
  6. data.head()
  7. # data.info()

out[295]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图5

步骤6 对应每一个location,一共有多少数据值缺失

  1. # 运行以下代码
  2. data.isnull().sum()

out[296]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图6

步骤7 对应每一个location,一共有多少完整的数据值

  1. # 运行以下代码
  2. data.shape[0] - data.isnull().sum()

out[297]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图7

步骤8 对于全体数据,计算风速的平均值

  1. # 运行以下代码
  2. data.mean().mean()

out[298]:

10.227982360836924

步骤9 创建一个名为loc_stats的数据框去计算并存储每个location的风速最小值,最大值,平均值和标准差

  1. # 运行以下代码
  2. loc_stats = pd.DataFrame()
  3. loc_stats['min'] = data.min() # min
  4. loc_stats['max'] = data.max() # max
  5. loc_stats['mean'] = data.mean() # mean
  6. loc_stats['std'] = data.std() # standard deviations
  7. loc_stats

out[299]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图8

步骤10 创建一个名为day_stats的数据框去计算并存储所有location的风速最小值,最大值,平均值和标准差

  1. # 运行以下代码
  2. # create the dataframe
  3. day_stats = pd.DataFrame()
  4. # this time we determine axis equals to one so it gets each row.
  5. day_stats['min'] = data.min(axis = 1) # min
  6. day_stats['max'] = data.max(axis = 1) # max
  7. day_stats['mean'] = data.mean(axis = 1) # mean
  8. day_stats['std'] = data.std(axis = 1) # standard deviations
  9. day_stats.head()

out[300]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图9

步骤11 对于每一个location,计算一月份的平均风速

(注意,1961年的1月和1962年的1月应该区别对待)

  1. # 运行以下代码
  2. # creates a new column 'date' and gets the values from the index
  3. data['date'] = data.index
  4. # creates a column for each value from date
  5. data['month'] = data['date'].apply(lambda date: date.month)
  6. data['year'] = data['date'].apply(lambda date: date.year)
  7. data['day'] = data['date'].apply(lambda date: date.day)
  8. # gets all value from the month 1 and assign to janyary_winds
  9. january_winds = data.query('month == 1')
  10. # gets the mean from january_winds, using .loc to not print the mean of month, year and day
  11. january_winds.loc[:,'RPT':"MAL"].mean()

out[301]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图10

步骤12 对于数据记录按照年为频率取样

  1. # 运行以下代码
  2. data.query('month == 1 and day == 1')

out[302]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图11

步骤13 对于数据记录按照月为频率取样

  1. # 运行以下代码
  2. data.query('day == 1')

out[303]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图12

练习7-可视化

探索泰坦尼克灾难数据

相应数据集:train.csv

步骤1 导入必要的库

  1. # 运行以下代码
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. import seaborn as sns
  5. import numpy as np
  6. %matplotlib inline

步骤2 从以下地址导入数据

  1. # 运行以下代码
  2. path7 = '../input/pandas_exercise/exercise_data/train.csv' # train.csv

步骤3 将数据框命名为titanic

  1. # 运行以下代码
  2. titanic = pd.read_csv(path7)
  3. titanic.head()

out[306]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图13

步骤4 将PassengerId设置为索引

  1. # 运行以下代码
  2. titanic.set_index('PassengerId').head()

out[307]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图14

步骤5 绘制一个展示男女乘客比例的扇形图

  1. # 运行以下代码
  2. # sum the instances of males and females
  3. males = (titanic['Sex'] == 'male').sum()
  4. females = (titanic['Sex'] == 'female').sum()
  5. # put them into a list called proportions
  6. proportions = [males, females]
  7. # Create a pie chart
  8. plt.pie(
  9. # using proportions
  10. proportions,
  11. # with the labels being officer names
  12. labels = ['Males', 'Females'],
  13. # with no shadows
  14. shadow = False,
  15. # with colors
  16. colors = ['blue','red'],
  17. # with one slide exploded out
  18. explode = (0.15 , 0),
  19. # with the start angle at 90%
  20. startangle = 90,
  21. # with the percent listed as a fraction
  22. autopct = '%1.1f%%'
  23. )
  24. # View the plot drop above
  25. plt.axis('equal')
  26. # Set labels
  27. plt.title("Sex Proportion")
  28. # View the plot
  29. plt.tight_layout()
  30. plt.show()

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图15

步骤6 绘制一个展示船票Fare, 与乘客年龄和性别的散点图

  1. # 运行以下代码
  2. # creates the plot using
  3. lm = sns.lmplot(x = 'Age', y = 'Fare', data = titanic, hue = 'Sex', fit_reg=False)
  4. # set title
  5. lm.set(title = 'Fare x Age')
  6. # get the axes object and tweak it
  7. axes = lm.axes
  8. axes[0,0].set_ylim(-5,)
  9. axes[0,0].set_xlim(-5,85)

out[309]:

(-5, 85)

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图16

步骤7 有多少人生还?

  1. # 运行以下代码
  2. titanic.Survived.sum()

out[310]:

342

步骤8 绘制一个展示船票价格的直方图

  1. # 运行以下代码
  2. # sort the values from the top to the least value and slice the first 5 items
  3. df = titanic.Fare.sort_values(ascending = False)
  4. df
  5. # create bins interval using numpy
  6. binsVal = np.arange(0,600,10)
  7. binsVal
  8. # create the plot
  9. plt.hist(df, bins = binsVal)
  10. # Set the title and labels
  11. plt.xlabel('Fare')
  12. plt.ylabel('Frequency')
  13. plt.title('Fare Payed Histrogram')
  14. # show the plot
  15. plt.show()

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图17

练习8-创建数据框

探索Pokemon数据

相应数据集:练习中手动内置的数据

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图18

步骤1 导入必要的库

  1. # 运行以下代码
  2. import pandas as pd

步骤2 创建一个数据字典

  1. # 运行以下代码
  2. raw_data = {"name": ['Bulbasaur', 'Charmander','Squirtle','Caterpie'],
  3. "evolution": ['Ivysaur','Charmeleon','Wartortle','Metapod'],
  4. "type": ['grass', 'fire', 'water', 'bug'],
  5. "hp": [45, 39, 44, 45],
  6. "pokedex": ['yes', 'no','yes','no']
  7. }

步骤3 将数据字典存为一个名叫pokemon的数据框中

  1. # 运行以下代码
  2. pokemon = pd.DataFrame(raw_data)
  3. pokemon.head()

out[314]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图19

步骤4 数据框的列排序是字母顺序,请重新修改为name, type, hp, evolution, pokedex这个顺序

  1. # 运行以下代码
  2. pokemon = pokemon[['name', 'type', 'hp', 'evolution','pokedex']]
  3. pokemon

out[315]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图20

步骤5 添加一个列place

  1. # 运行以下代码
  2. pokemon['place'] = ['park','street','lake','forest']
  3. pokemon

out[316]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图21

步骤6 查看每个列的数据类型

out[317]:
name object
type object
hp int64
evolution object
pokedex object
place object
dtype: object

练习9-时间序列

探索Apple公司股价数据

相应数据集:Apple_stock.csv

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图22

步骤1 导入必要的库

  1. # 运行以下代码
  2. import pandas as pd
  3. import numpy as np
  4. # visualization
  5. import matplotlib.pyplot as plt
  6. %matplotlib inline

步骤2 数据集地址

  1. # 运行以下代码
  2. path9 = '../input/pandas_exercise/exercise_data/Apple_stock.csv' # Apple_stock.csv

步骤3 读取数据并存为一个名叫apple的数据框

  1. # 运行以下代码
  2. apple = pd.read_csv(path9)
  3. apple.head()

out[320]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图23

步骤4 查看每一列的数据类型

out[321]:

Date object
Open float64
High float64
Low float64
Close float64
Volume int64
Adj Close float64
dtype: object

步骤5 将Date这个列转换为datetime类型

  1. # 运行以下代码
  2. apple.Date = pd.to_datetime(apple.Date)
  3. apple['Date'].head()

out[322]:

0 2014-07-08
1 2014-07-07
2 2014-07-03
3 2014-07-02
4 2014-07-01
Name: Date, dtype: datetime64[ns]

步骤6 将Date设置为索引

  1. # 运行以下代码
  2. apple = apple.set_index('Date')
  3. apple.head()

out[323]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图24

步骤7 有重复的日期吗?

  1. # 运行以下代码
  2. apple.index.is_unique

out[324]:

True

步骤8 将index设置为升序

  1. # 运行以下代码
  2. apple.sort_index(ascending = True).head()

out[325]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图25

步骤9 找到每个月的最后一个交易日(business day)

  1. # 运行以下代码
  2. apple_month = apple.resample('BM')
  3. apple_month.head()

out[326]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图26

步骤10 数据集中最早的日期和最晚的日期相差多少天?

  1. # 运行以下代码
  2. (apple.index.max() - apple.index.min()).days

out[327]:

12261

步骤11 在数据中一共有多少个月?

  1. # 运行以下代码
  2. apple_months = apple.resample('BM').mean()
  3. len(apple_months.index)

out[328]:

404

步骤12 按照时间顺序可视化Adj Close

  1. # 运行以下代码
  2. # makes the plot and assign it to a variable
  3. appl_open = apple['Adj Close'].plot(title = "Apple Stock")
  4. # changes the size of the graph
  5. fig = appl_open.get_figure()
  6. fig.set_size_inches(13.5, 9)

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图27

练习10-删除数据

探索Iris纸鸢花数据

相应数据集:iris.csv

步骤1 导入必要的库

  1. # 运行以下代码
  2. import pandas as pd

步骤2 数据集地址

  1. # 运行以下代码
  2. path10 ='../input/pandas_exercise/exercise_data/iris.csv' # iris.csv

步骤3 将数据集存成变量iris

  1. # 运行以下代码
  2. iris = pd.read_csv(path10)
  3. iris.head()

out[332]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图28

步骤4 创建数据框的列名称

  1. iris = pd.read_csv(path10,names = ['sepal_length','sepal_width', 'petal_length', 'petal_width', 'class'])
  2. iris.head()

out[333]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图29

步骤5 数据框中有缺失值吗?

  1. # 运行以下代码
  2. pd.isnull(iris).sum()

out[334]:

sepal_length 0
sepal_width 0
petal_length 0
petal_width 0
class 0
dtype: int64

步骤6 将列petal_length的第10到19行设置为缺失值

  1. # 运行以下代码
  2. iris.iloc[10:20,2:3] = np.nan
  3. iris.head(20)

out[335]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图30

步骤7 将缺失值全部替换为1.0

  1. # 运行以下代码
  2. iris.petal_length.fillna(1, inplace = True)
  3. iris

out[336]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图31

步骤8 删除列class

  1. # 运行以下代码
  2. del iris['class']
  3. iris.head()

out[337]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图32

步骤9 将数据框前三行设置为缺失值

  1. # 运行以下代码
  2. iris.iloc[0:3 ,:] = np.nan
  3. iris.head()

out[338]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图33

步骤10 删除有缺失值的行

  1. # 运行以下代码
  2. iris = iris.dropna(how='any')
  3. iris.head()

out[339]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图34

步骤11 重新设置索引

  1. # 运行以下代码
  2. iris = iris.reset_index(drop = True)
  3. iris.head()

out[340]:

10套练习,教你如何用Pandas做数据分析【6-10】 - 知乎 - 图35

转载本文请联系和鲸社区取得授权。