Pandas是入门Python做数据分析必须要掌握的一个库,是一个开放源码、BSD 许可的库,提供高性能、易于使用的数据结构和数据分析的工具。主要数据结构是 Series (一维数据)与 DataFrame(二维数据),这两种数据结构足以处理金融、统计、社会科学、工程等领域里的大多数典型用例。今天就来一起学习。 ![在这里插入图片描述](https://img-blog.csdnimg.cn/5204553160914fc78624c8e31e9f5bdf.gif#pic_center)
练习6-统计
探索风速数据
import pandas as pd
import datetime
import pandas as pd
path6 = "../input/pandas_exercise/pandas_exercise/exercise_data/wind.data"
import datetime
data = pd.read_table(path6, sep = "\s+", parse_dates = [[0,1,2]])
data.head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/e1d55b7fd63a4d9a8c5f78323e1af446.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_19,color_FFFFFF,t_70,g_se,x_16)
- 第四步:2061年?我们真的有这一年的数据?创建一个函数并用它去修复这个bug
def fix_century(x):
year = x.year - 100 if x.year > 1989 else x.year
return datetime.date(year, x.month, x.day)
data['Yr_Mo_Dy'] = data['Yr_Mo_Dy'].apply(fix_century)
data.head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/5d78fa70a15c4384a79d836c337831b5.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_19,color_FFFFFF,t_70,g_se,x_16)
- 第五步:将日期设为索引,注意数据类型,应该是datetime64[ns]
data["Yr_Mo_Dy"] = pd.to_datetime(data["Yr_Mo_Dy"])
data = data.set_index('Yr_Mo_Dy')
data.head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/63261630c19d48b7a9ec172edf626e5b.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_18,color_FFFFFF,t_70,g_se,x_16)
- 第六步:对应每一个location,一共有多少数据值缺失
data.isnull().sum()
![在这里插入图片描述](https://img-blog.csdnimg.cn/2d03aa2c789b4a8eae8dc4869e1e761d.png)
- 第七步:对应每一个location,一共有多少完整的数据值
data.shape[0] - data.isnull().sum()
![在这里插入图片描述](https://img-blog.csdnimg.cn/602f7cdbde5948648d32068d48f2ff33.png)
data.mean().mean()
10.227982360836924
- 第九步:创建一个名为loc_stats的数据框去计算并存储每个location的风速最小值,最大值,平均值和标准差
loc_stats = pd.DataFrame()
loc_stats['min'] = data.min()
loc_stats['max'] = data.max()
loc_stats['mean'] = data.mean()
loc_stats['std'] = data.std()
loc_stats
![在这里插入图片描述](https://img-blog.csdnimg.cn/fc37a84ecbc8454c82d180796f011561.png#pic_center)
- 第十步:创建一个名为day_stats的数据框去计算并存储所有location的风速最小值,最大值,平均值和标准差
day_stats = pd.DataFrame()
day_stats['min'] = data.min(axis = 1)
day_stats['max'] = data.max(axis = 1)
day_stats['mean'] = data.mean(axis = 1)
day_stats['std'] = data.std(axis = 1)
day_stats.head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/9b2f51adca444850afd796851384d8d7.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_9,color_FFFFFF,t_70,g_se,x_16)
- 第十一步:对于每一个location,计算一月份的平均风速
注意:1961年的1月和1962年的1月应该区别对待
data['date'] = data.index
data['month'] = data['date'].apply(lambda date: date.month)
data['year'] = data['date'].apply(lambda date: date.year)
data['day'] = data['date'].apply(lambda date: date.day)
january_winds = data.query('month == 1')
january_winds.loc[:,'RPT':"MAL"].mean()
![在这里插入图片描述](https://img-blog.csdnimg.cn/511a727eb3884e0382259b2965d66226.png)
data.query('month == 1 and day == 1')
![在这里插入图片描述](https://img-blog.csdnimg.cn/944b715e37d540e0aa2dc1eb81c38b64.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_20,color_FFFFFF,t_70,g_se,x_16)
data.query('day == 1')
![在这里插入图片描述](https://img-blog.csdnimg.cn/0b666463feb44de09ce1e38c4f7f5db1.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center) ![在这里插入图片描述](https://img-blog.csdnimg.cn/7c25f9022ea94d8d9a3ccd7e26e44d95.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center)
练习7-可视化
探索泰坦尼克灾难数据
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
%matplotlib inline
path7 = '../input/pandas_exercise/pandas_exercise/exercise_data/train.csv'
titanic = pd.read_csv(path7)
titanic.head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/88d0afc7b56e4f9abfd92c446cce0af3.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center)
titanic.set_index('PassengerId').head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/1c3c270290614cb9a67e629867bd8fce.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center)
males = (titanic['Sex'] == 'male').sum()
females = (titanic['Sex'] == 'female').sum()
proportions = [males, females]
plt.pie(
proportions,
labels = ['Males', 'Females'],
shadow = False,
colors = ['blue','red'],
explode = (0.15 , 0),
startangle = 90,
autopct = '%1.1f%%'
)
plt.axis('equal')
plt.title("Sex Proportion")
plt.tight_layout()
plt.show()
![在这里插入图片描述](https://img-blog.csdnimg.cn/f2f533bcf8f6442c95f6b6dca3fc76bf.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_11,color_FFFFFF,t_70,g_se,x_16#pic_center)
- 第六步:绘制一个展示船票Fare, 与乘客年龄和性别的散点图
lm = sns.lmplot(x = 'Age', y = 'Fare', data = titanic, hue = 'Sex', fit_reg=False)
lm.set(title = 'Fare x Age')
axes = lm.axes
axes[0,0].set_ylim(-5,)
axes[0,0].set_xlim(-5,85)
(-5, 85)
![在这里插入图片描述](https://img-blog.csdnimg.cn/45fb098bcfdc4ab9ab4b90a734b387ce.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_14,color_FFFFFF,t_70,g_se,x_16#pic_center)
titanic.Survived.sum()
342
df = titanic.Fare.sort_values(ascending = False)
df
binsVal = np.arange(0,600,10)
binsVal
plt.hist(df, bins = binsVal)
plt.xlabel('Fare')
plt.ylabel('Frequency')
plt.title('Fare Payed Histrogram')
plt.show()
![在这里插入图片描述](https://img-blog.csdnimg.cn/5cb75f64a8584c749df628e896a39047.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_14,color_FFFFFF,t_70,g_se,x_16#pic_center)
练习8-创建数据框
探索Pokemon数据
import pandas as pd
raw_data = {"name": ['Bulbasaur', 'Charmander','Squirtle','Caterpie'],
"evolution": ['Ivysaur','Charmeleon','Wartortle','Metapod'],
"type": ['grass', 'fire', 'water', 'bug'],
"hp": [45, 39, 44, 45],
"pokedex": ['yes', 'no','yes','no']
}
- 第三步:将数据字典存为一个名叫pokemon的数据框中
pokemon = pd.DataFrame(raw_data)
pokemon.head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/2a09747c3a7741fe96b1dbed434b8b00.png#pic_center)
- 第四步:数据框的列排序是字母顺序,请重新修改为name, type, hp, evolution, pokedex这个顺序
pokemon = pokemon[['name', 'type', 'hp', 'evolution','pokedex']]
pokemon
![在这里插入图片描述](https://img-blog.csdnimg.cn/581820f171d84030ae5997d6214b4362.png#pic_center)
pokemon['place'] = ['park','street','lake','forest']
pokemon
![在这里插入图片描述](https://img-blog.csdnimg.cn/60f5aea8e22943659bea4121eea435b9.png#pic_center)
pokemon.dtypes
![在这里插入图片描述](https://img-blog.csdnimg.cn/f611880c1a5e437494e0814b36aedfd4.png)
练习9-时间序列
探索Apple公司股价数据
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
path9 = '../input/pandas_exercise/pandas_exercise/exercise_data/Apple_stock.csv'
apple = pd.read_csv(path9)
apple.head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/f956ebc04e124481820751e456af294c.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_13,color_FFFFFF,t_70,g_se,x_16)
apple.dtypes
![在这里插入图片描述](https://img-blog.csdnimg.cn/3a12bdb2156744e396242dd4ef9729fe.png)
- 第五步:将Date这个列转换为datetime类型
apple.Date = pd.to_datetime(apple.Date)
apple['Date'].head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/23983a1a12a549a3a64f96b271821a52.png)
apple = apple.set_index('Date')
apple.head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/28296e5b3f93407dade629dabda09cd2.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_12,color_FFFFFF,t_70,g_se,x_16)
apple.index.is_unique
True
apple.sort_index(ascending = True).head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/3b55b4a43f47481f9412762a191a6c90.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_12,color_FFFFFF,t_70,g_se,x_16)
- 第九步:找到每个月的最后一个交易日(business day)
apple_month = apple.resample('BM')
apple_month.head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/6520613eff1044d891971c802a488641.png)
![在这里插入图片描述](https://img-blog.csdnimg.cn/5350b5044f1f4a3c958eb076d9f738f3.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_17,color_FFFFFF,t_70,g_se,x_16)
(apple.index.max() - apple.index.min()).days
12261
apple_months = apple.resample('BM').mean()
len(apple_months.index)
404
appl_open = apple['Adj Close'].plot(title = "Apple Stock")
fig = appl_open.get_figure()
fig.set_size_inches(13.5, 9)
![在这里插入图片描述](https://img-blog.csdnimg.cn/9ee9967e3d7a43aaa029ce51b66161ca.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center)
练习10-删除数据
探索Iris纸鸢花数据
import pandas as pd
path10 ='../input/pandas_exercise/pandas_exercise/exercise_data/iris.csv'
iris = pd.read_csv(path10)
iris.head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/4c39a8ebbdc2463c93e9af3af86650ac.png#pic_center)
iris = pd.read_csv(path10,names = ['sepal_length','sepal_width', 'petal_length', 'petal_width', 'class'])
iris.head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/a08c95070bf541608d83ebf82f7b68ec.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_13,color_FFFFFF,t_70,g_se,x_16#pic_center)
pd.isnull(iris).sum()
![在这里插入图片描述](https://img-blog.csdnimg.cn/729f66cd1dd14c1a8c71a8d484748b01.png)
- 第六步:将列petal_length的第10到19行设置为缺失值
iris.iloc[10:20,2:3] = np.nan
iris.head(20)
![在这里插入图片描述](https://img-blog.csdnimg.cn/685b08b0ce4d40cbacf73fbe73d907c2.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_12,color_FFFFFF,t_70,g_se,x_16#pic_center)
iris.petal_length.fillna(1, inplace = True)
iris
![在这里插入图片描述](https://img-blog.csdnimg.cn/a5337c5916a54231940373b9082652d4.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_12,color_FFFFFF,t_70,g_se,x_16#pic_center) ![在这里插入图片描述](https://img-blog.csdnimg.cn/a25f42a4f08d47098cac33eb669e8ec5.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_12,color_FFFFFF,t_70,g_se,x_16#pic_center)
del iris['class']
iris.head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/8e85befe02544c07afd093d8f9664f2d.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_11,color_FFFFFF,t_70,g_se,x_16#pic_center)
iris.iloc[0:3 ,:] = np.nan
iris.head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/8ee741f99aa54161a29aa399bd63de1e.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_11,color_FFFFFF,t_70,g_se,x_16#pic_center)
iris = iris.dropna(how='any')
iris.head()
![在这里插入图片描述](https://img-blog.csdnimg.cn/f7a5cdb06d8341d0a256727cf9b90eb1.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5LiW5LiK5pys5peg6ay8,size_11,color_FFFFFF,t_70,g_se,x_16#pic_center)
iris = iris.reset_index(drop = True)
iris.head()
你们的支持是我持续更新下去的动力,(点赞,关注,评论) 这篇文还未结束,想了解后续的可以关注我,持续更新。 ![在这里插入图片描述](https://img-blog.csdnimg.cn/3d6f274cf53645039f6f862185a43c19.gif#pic_center)
点击领取🎁🎁 Q群号: 943192807(纯技术交流和资源共享)以自助拿走。
①行业咨询、专业解答 ②Python开发环境安装教程 ③400集自学视频 ④软件开发常用词汇 ⑤最新学习路线图 ⑥3000多本Python电子书
|