数据分析03Pandas玩转数据

it2022-05-05  158

Series的运算

#导入库 import numpy as np import pandas as pd from pandas import Series, DataFrame #定义两个Series s1 = Series([1,2,3], index=['A','B','C']) ''' 得到 A 1 B 2 C 3 dtype: int64 ''' s2 = Series([4,5,6,7], index=['B','C','D','E']) ''' 得到 B 4 C 5 D 6 E 7 dtype: int64 ''' #运算符合NaN和其他运算均为NaN s1 + s2 ''' 得到 A NaN B 6.0 C 8.0 D NaN E NaN dtype: float64 '''

Dataframe的运算

#导入库 import numpy as np import pandas as pd from pandas import Series, DataFrame #定义两个DataFrame df1 = DataFrame(np.arange(4).reshape(2,2), index=['A','B'], columns=['BJ','SH'])

得到

df2 = DataFrame(np.arange(9).reshape(3,3), index=['A','B','C'], columns=['BJ','SH','GZ'])

得到

#加法符合点加点乘等 df1 + df2

得到

#定义一个新的DataFrame df3 = DataFrame([[1,2,3],[4,5,np.nan],[7,8,9]],index=['A','B','C'],columns=['c1','c2','c3'])

得到

#求列和,但NaN不参加计算 df3.sum() ''' 得到 c1 12.0 c2 15.0 c3 12.0 dtype: float64 ''' #求行和,但NaN不参加计算,axis=1为行 df3.sum(axis=1) ''' 得到 A 6.0 B 9.0 C 24.0 dtype: float64 ''' #求最小值,同sum,NaN不参加计算,默认为列,axis=1为行 df3.min() ''' 得到 c1 1.0 c2 2.0 c3 3.0 dtype: float64 ''' #求最大值,同sum,NaN不参加计算,默认为列,axis=1为行 df3.max() ''' 得到 c1 7.0 c2 8.0 c3 9.0 dtype: float64 ''' #求统计数据,同其他,NaN不参加计算,默认为列,axis=1为行 df3.describe()

得到

Series的排序

#导入库 import numpy as np import pandas as pd from pandas import Series, DataFrame #定义一个Series s1 = Series(np.random.randn(10)) ''' 得到 0 -0.004673 1 1.509025 2 0.733753 3 -0.103241 4 -1.361901 5 -0.699008 6 1.110159 7 -1.888685 8 0.094221 9 0.667346 dtype: float64 ''' #原属性 s1.values ''' 得到 array([-0.00467285, 1.50902503, 0.73375274, -0.10324052, -1.36190085, -0.69900758, 1.11015864, -1.88868549, 0.09422074, 0.66734552]) ''' s1.index ''' 得到 RangeIndex(start=0, stop=10, step=1) ''' #False为降序,默认为升序排列 s2 = s1.sort_values(ascending=False) ''' 得到 1 1.509025 6 1.110159 2 0.733753 9 0.667346 8 0.094221 0 -0.004673 3 -0.103241 5 -0.699008 4 -1.361901 7 -1.888685 dtype: float64 ''' #将新的Series的Index进行升序排序 s2.sort_index() ''' 得到 0 -0.004673 1 1.509025 2 0.733753 3 -0.103241 4 -1.361901 5 -0.699008 6 1.110159 7 -1.888685 8 0.094221 9 0.667346 dtype: float64 '''

Dataframe的排序

#导入库 import numpy as np import pandas as pd from pandas import Series, DataFrame #定义一个DataFrame df1 = DataFrame(np.random.randn(40).reshape(8,5), columns=['A','B','C','D','E'])

得到

#DataFrame整体的排序(指定A列) df2 = df1.sort_values('A')

得到

#再将新的DataFrame的Index排序 df2.sort_index()

得到

重命名DataFrame的Index

#导入库 import numpy as np import pandas as pd from pandas import Series, DataFrame #创建新的DataFrame df1 = DataFrame(np.arange(9).reshape(3,3), index=['BJ','SH','GZ'], columns=['A','B','C'])

得到

df1.index ''' 得到 Index(['BJ', 'SH', 'GZ'], dtype='object') ''' #修改Index的第一种方法 df1.index = Series(['bj','sh','gz'])

得到

df1.index ''' 得到 Index(['bj', 'sh', 'gz'], dtype='object') ''' #Map的方法,传入一个函数 df1.index = df1.index.map(str.upper)

得到

#rename传入函数的方法 df1.rename(index=str.lower, columns=str.lower)

得到

#rename传入字典的方法 df1.rename(index={'BJ': 'beijing'}, columns={"A":'a'})

得到

#for循环方法的回顾list1转换为list2 list1 = [1,2,3,4] list2 = ['1','2','3','4'] [str(x) for x in list1] ''' 得到 ['1', '2', '3', '4'] ''' #map方法的回顾list1转换为list2 list(map(str, list1)) ''' 得到 ['1', '2', '3', '4'] ''' #写一个自己的函数,来让map接收 def test_map(x): return x + '_ABC' df1.index.map(test_map) ''' 得到 Index(['BJ_ABC', 'SH_ABC', 'GZ_ABC'], dtype='object') ''' #写一个自己的函数,来让rename接收 df1.rename(index=test_map)

得到

DataFrame的merge操作(合并)

#导入库 import pandas as pd import numpy as np from pandas import Series, DataFrame #定义两个DataFrame df1 = DataFrame({'key':['X','Y','Z','X'], 'data_set_1':[1,2,3,4]})

得到

df2 = DataFrame({'key':['X','B','C'], 'data_set_2':[4,5,6]})

得到

#找相同的column,再找column下数值一样的元素,并放在同一个DataFrame里 pd.merge(df1, df2, on=None)

得到

#on参数的意思是指定对比的column,inner默认,只合并都有的元素,其它忽略 pd.merge(df1, df2, on='key',how='inner')

得到

#how='left',以第一个DataFrame的数值为主合并,没有的填充NaN pd.merge(df1, df2, on='key', how='left')

得到

#how='right',以第二个DataFrame的数值为主合并,没有的填充NaN pd.merge(df1, df2, on='key', how='right')

得到

#how='outer',以两个DataFrame的数值全部合并,没有的填充NaN pd.merge(df1, df2, on='key', how='outer')

得到

Concatenate 连接

#导入库 import pandas as pd import numpy as np from pandas import Series, DataFrame #创建两个Array arr1 = np.arange(9).reshape(3,3) ''' 得到 array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) ''' arr2 = np.arange(9).reshape(3,3) ''' 得到 array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) ''' #矩阵的concatenate,每个行,首尾连接 np.concatenate([arr1,arr2],axis=1) ''' 得到 array([[0, 1, 2, 0, 1, 2], [3, 4, 5, 3, 4, 5], [6, 7, 8, 6, 7, 8]]) ''' #创建两个Series s1 = Series([1,2,3], index=['X','Y','Z']) ''' 得到 X 1 Y 2 Z 3 dtype: int64 ''' s2 = Series([4,5], index=['A','B']) ''' 得到 A 4 B 5 dtype: int64 ''' #Series的concatenate,整个Series首尾连接 pd.concat([s1,s2]) ''' 得到 X 1 Y 2 Z 3 A 4 B 5 dtype: int64 ''' #创建两个DataFrame df1 = DataFrame(np.random.randn(4,3), columns=['X','Y','Z'])

得到

df2 = DataFrame(np.random.randn(3,3), columns=['X','Y','A'])

得到

#DataFrame的concatenate,整个DataFrame同column连接,缺少值填充NaN pd.concat([df1,df2])

得到

Combine 填充

#导入库 import pandas as pd import numpy as np from pandas import Series, DataFrame #创建两个Series s1 = Series([2, np.nan, 4, np.nan], index=['A','B','C','D']) ''' 得到 A 2.0 B NaN C 4.0 D NaN dtype: float64 ''' s2 = Series([1,2,3,4], index=['A','B','C','D']) ''' 得到 A 1 B 2 C 3 D 4 dtype: int64 ''' #用S2填充S1,将S1里缺少的位置,用S2对应位置的数值填充 s1.combine_first(s2) ''' 得到 A 2.0 B 2.0 C 4.0 D 4.0 dtype: float64 ''' #创建两个DataFrame df1 = DataFrame({ 'X': [1, np.nan, 3, np.nan], 'Y': [5, np.nan, 7, np.nan], 'Z': [9, np.nan, 11,np.nan] })

得到

df2 = DataFrame({ 'Z':[np.nan, 10, np.nan, 12], 'A':[1,2,3,4] })

得到

#用df2填充df1,将df1里缺少的位置,用df2对应位置的数值填充,另外会将df2比df1多的列也加入结果中 df1.combine_first(df2)

得到

apply 数据预处理

#导入库 import numpy as np import pandas as pd from pandas import Series, DataFrame #从文件获取一个DataFrame df = pd.read_csv('../homework/apply_demo.csv') df.head()

得到

#行数 df.size ''' 得到 7978 ''' #创建一个新的Series s1 = Series(['a']*7978) df['A'] = s1 df.head()

得到

#Series'A'的变成大写 df['A'] = df['A'].apply(str.upper) df.head()

得到

#把data变成三列,用空格区分并且去掉 l1 = df['data'][0].strip().split(' ') l1[1], l1[3],l1[5] ''' 得到 ('APPL', '0', '1623') ''' #把data变成三列,定义函数 def foo(line): items = line.strip().split(' ') return Series([items[1], items[3], items[5]]) #用apply应用函数 df_tmp = df['data'].apply(foo) #columns重命名 df_tmp = df_tmp.rename(columns={0:"Symbol", 1:"Seqno", 2:"Price"}) df_tmp.head()

得到

#df不变 df.head()

得到

#联合df_tmp和df df_new = df.combine_first(df_tmp) df_new.head()

得到

#删除两列 del df_new['data'] del df_new['A'] df_new.head()

得到

#将结果传回文件 df_new.to_csv('../homework/demo_duplicate.csv') 得到 apply_demo.csv demo_duplicate.csv iris.csv movie_metadata.csv

drop_duplicates 去重

#导入库 import numpy as np import pandas as pd from pandas import Series, DataFrame #读取文件 df = pd.read_csv('../homework/demo_duplicate.csv') #删除一列 del df['Unnamed: 0'] #列数 df.size ''' 得到 15956 ''' #长度 len(df) ''' 得到 3989 ''' #['Seqno']行有多少种数字 len(df['Seqno'].unique()) ''' 得到 1000 ''' df.head(10)

得到

#['Seqno']行数据是否为重复的 df['Seqno'].duplicated() ''' 得到 0 False 1 True 2 True 3 True 4 False 5 True 6 True 。。。 Name: Seqno, Length: 3989, dtype: bool ''' #去掉重复操作,以['Seqno']行数据为基准,keep默认是first,去重只保留第一个,last保留最后一个 df.drop_duplicates(['Seqno'],keep='last')

得到 1000 rows × 4 columns

datetime 时间序列

#导入库 import numpy as np import pandas as pd from pandas import Series, DataFrame #导入datetime库 from datetime import datetime #创建一个时间,年月日 t1 = datetime(2009,10,20) ''' 得到 datetime.datetime(2009, 10, 20, 0, 0) ''' #创建多个时间,列表 date_list = [ datetime(2016,9,1), datetime(2016,9,10), datetime(2017,9,1), datetime(2017,9,20), datetime(2017,10,1) ] ''' 得到 [datetime.datetime(2016, 9, 1, 0, 0), datetime.datetime(2016, 9, 10, 0, 0), datetime.datetime(2017, 9, 1, 0, 0), datetime.datetime(2017, 9, 20, 0, 0), datetime.datetime(2017, 10, 1, 0, 0)] ''' #创建随机时间 s1 = Series(np.random.rand(5), index=date_list) ''' 得到 2016-09-01 0.848723 2016-09-10 0.473743 2017-09-01 0.497274 2017-09-20 0.367025 2017-10-01 0.163207 dtype: float64 ''' #数值是随机数 s1.values 得到 array([0.84872287, 0.47374346, 0.49727431, 0.36702522, 0.1632072 ]) #索引是时间 s1.index ''' 得到 DatetimeIndex(['2016-09-01', '2016-09-10', '2017-09-01', '2017-09-20', '2017-10-01'], dtype='datetime64[ns]', freq=None) ''' #从标签访问 s1[1] ''' 得到 0.473743463058135 ''' #从索引访问 s1[datetime(2016,9,10)] ''' 得到 0.473743463058135 ''' #直写时间,不加datatime s1['2016-9-10'] ''' 得到 0.473743463058135 ''' #直写时间,不加横杠,不加datatime s1['20160910'] 得到 0.473743463058135 #直写时间,只有月份,不加datatime s1['2017-09'] ''' 得到 2017-09-01 0.497274 2017-09-20 0.367025 dtype: float64 ''' #直写时间,只有年份,不加datatime s1['2016'] ''' 得到 2016-09-01 0.848723 2016-09-10 0.473743 dtype: float64 ''' #直写时间,只有年份,不加datatime s1['2017'] ''' 得到 2017-09-01 0.497274 2017-09-20 0.367025 2017-10-01 0.163207 dtype: float64 ''' #时间范围规定,periods时间间隔(start,periods和start和end互斥) #freq步长默认D是天,5H代表五小时,周从周日开始,W-MON指定从周几开始 date_list_new = pd.date_range('2016-01-01', periods=100, freq='5H') s2 = Series(np.random.rand(100), index=date_list_new) ''' 得到 2016-01-01 00:00:00 0.071369 2016-01-01 05:00:00 0.292150 2016-01-01 10:00:00 0.176345 2016-01-01 15:00:00 0.144360 2016-01-01 20:00:00 0.798835 2016-01-02 01:00:00 0.341525 2016-01-02 06:00:00 0.610857 。。。 Freq: 5H, Length: 100, dtype: float64 '''

时间序列数据的采样和画图

#导入库 import numpy as np import pandas as pd from pandas import Series, DataFrame from datetime import datetime #创建一个时间的Index t_range = pd.date_range('2016-01-01', '2016-12-31') ''' 得到 DatetimeIndex(['2016-01-01', '2016-01-02', '2016-01-03', '2016-01-04', '2016-01-05', '2016-01-06', '2016-01-07', '2016-01-08', '2016-01-09', '2016-01-10', ... '2016-12-22', '2016-12-23', '2016-12-24', '2016-12-25', '2016-12-26', '2016-12-27', '2016-12-28', '2016-12-29', '2016-12-30', '2016-12-31'], dtype='datetime64[ns]', length=366, freq='D') ''' #数据采样,创建一个Series s1 = Series(np.random.randn(len(t_range)), index=t_range) #Index采样,mean即整月平均值 s1['2016-01'].mean() ''' 得到 -0.13632025497138667 ''' #按月采样,M指month,得到整个采样Series s1_month = s1.resample('M').mean() #每个月的最后一天的Index s1_month.index ''' 得到 DatetimeIndex(['2016-01-31', '2016-02-29', '2016-03-31', '2016-04-30', '2016-05-31', '2016-06-30', '2016-07-31', '2016-08-31', '2016-09-30', '2016-10-31', '2016-11-30', '2016-12-31'], dtype='datetime64[ns]', freq='M') ''' #按小时填充数据ffill()往前填充数据,从2016-01-01 00:00:00填充2016-01-01 01:00:00 #按小时填充数据bfill()往后填充数据,从2016-01-02 00:00:00填充2016-01-01 23:00:00 s1.resample('H').bfill() ''' 得到 2016-01-01 00:00:00 0.566248 2016-01-01 01:00:00 -0.062260 2016-01-01 02:00:00 -0.062260 2016-01-01 03:00:00 -0.062260 2016-01-01 04:00:00 -0.062260 。。。 Freq: H, Length: 8761, dtype: float64 ''' #创建一个时间序列数据 t_range = pd.date_range('2016-01-01', '2016-12-31', freq='H') ''' 得到 DatetimeIndex(['2016-01-01 00:00:00', '2016-01-01 01:00:00', '2016-01-01 02:00:00', '2016-01-01 03:00:00', '2016-01-01 04:00:00', '2016-01-01 05:00:00', '2016-01-01 06:00:00', '2016-01-01 07:00:00', '2016-01-01 08:00:00', '2016-01-01 09:00:00', ... '2016-12-30 15:00:00', '2016-12-30 16:00:00', '2016-12-30 17:00:00', '2016-12-30 18:00:00', '2016-12-30 19:00:00', '2016-12-30 20:00:00', '2016-12-30 21:00:00', '2016-12-30 22:00:00', '2016-12-30 23:00:00', '2016-12-31 00:00:00'], dtype='datetime64[ns]', length=8761, freq='H') ''' #创建一个DataFrame,只有Index stock_df = DataFrame(index=t_range) #创建一列,随机整数randint,大小是Index的长度 stock_df['BABA'] = np.random.randint(80, 160, size=len(t_range)) stock_df['TENCENT'] = np.random.randint(30, 50, size=len(t_range)) stock_df.head()

得到

#创建一个图表 stock_df.plot() 得到 <matplotlib.axes._subplots.AxesSubplot at 0x1108e3198> #导入一个plot的库 import matplotlib.pyplot as plt #展示图表 plt.show()

得到

#创建空的DataFrame weekly_df = DataFrame() #按周采样,平均值 weekly_df['BABA'] = stock_df['BABA'].resample('W').mean() weekly_df['TENCENT'] = stock_df['TENCENT'].resample('W').mean() weekly_df.head()

得到

#产生图表 weekly_df.plot() 得到 <matplotlib.axes._subplots.AxesSubplot at 0x1108e30f0> #展示图表 plt.show()

得到

Binning 数据分箱

#导入库 import numpy as np import pandas as pd from pandas import Series, DataFrame #创建一个array 随机成绩 score_list = np.random.randint(25, 100, size=20) ''' 得到 array([70, 58, 72, 72, 81, 53, 51, 55, 97, 46, 81, 76, 61, 38, 39, 93, 31, 83, 78, 65]) ''' #数据分箱的分段 bins = [0,59,70,80,100] #数据切片 score_cat = pd.cut(score_list, bins) #每个分箱有多少人 pd.value_counts(score_cat) ''' 得到 (0, 59] 8 (80, 100] 5 (70, 80] 4 (59, 70] 3 dtype: int64 ''' #创建一个空DataFrame df = DataFrame() #填入['score']列 df['score'] = score_list #产生姓名,随机字符串 df['student'] = [pd.util.testing.rands(3) for i in range(20)] #分箱的命名,以之前的分箱的分段为格式 df['Categories'] = pd.cut(df['score'],bins, labels=['Low','OK','Good','Great'])

得到

GroupBy 数据分组

#导入库 import numpy as np import pandas as pd from pandas import Series, DataFrame #导入文件中的DataFrame df = pd.read_csv('../homework/city_weather.csv')

得到

#将['city']列分组 g = df.groupby(df['city']) ''' 得到 <pandas.core.groupby.DataFrameGroupBy object at 0x10d45a128> ''' #得到分组的Index情况 g.groups ''' 得到 {'BJ': Int64Index([0, 1, 2, 3, 4, 5], dtype='int64'), 'GZ': Int64Index([14, 15, 16, 17], dtype='int64'), 'SH': Int64Index([6, 7, 8, 9, 10, 11, 12, 13], dtype='int64'), 'SZ': Int64Index([18, 19], dtype='int64')} ''' #过滤出某一个分组的情况 df_bj = g.get_group('BJ') #单一一个分组的平均值是一个Series type(df_bj.mean()) ''' 得到 pandas.core.series.Series ''' #求所有分组的均值,最大值max,最小值min g.mean()

得到

GroupBy分解图

g 得到 <pandas.core.groupby.DataFrameGroupBy object at 0x10d45a128> #列表的字典转换 dict(list(g))['BJ']

得到

#转换为列表 list(g) ''' 得到 [('BJ', date city temperature wind 0 03/01/2016 BJ 8 5 1 17/01/2016 BJ 12 2 2 31/01/2016 BJ 19 2 3 14/02/2016 BJ -3 3 4 28/02/2016 BJ 19 2 5 13/03/2016 BJ 5 3), ('GZ', date city temperature wind 14 17/07/2016 GZ 10 2 15 31/07/2016 GZ -1 5 16 14/08/2016 GZ 1 5 17 28/08/2016 GZ 25 4), ('SH', date city temperature wind 6 27/03/2016 SH -4 4 7 10/04/2016 SH 19 3 8 24/04/2016 SH 20 3 9 08/05/2016 SH 17 3 10 22/05/2016 SH 4 2 11 05/06/2016 SH -10 4 12 19/06/2016 SH 0 5 13 03/07/2016 SH -9 5), ('SZ', date city temperature wind 18 11/09/2016 SZ 20 1 19 25/09/2016 SZ -10 4)] ''' #遍历所有的group for name, group_df in g: print(name) print(group_df) ''' 得到 BJ date city temperature wind 0 03/01/2016 BJ 8 5 1 17/01/2016 BJ 12 2 2 31/01/2016 BJ 19 2 3 14/02/2016 BJ -3 3 4 28/02/2016 BJ 19 2 5 13/03/2016 BJ 5 3 GZ date city temperature wind 14 17/07/2016 GZ 10 2 15 31/07/2016 GZ -1 5 16 14/08/2016 GZ 1 5 17 28/08/2016 GZ 25 4 SH date city temperature wind 6 27/03/2016 SH -4 4 7 10/04/2016 SH 19 3 8 24/04/2016 SH 20 3 9 08/05/2016 SH 17 3 10 22/05/2016 SH 4 2 11 05/06/2016 SH -10 4 12 19/06/2016 SH 0 5 13 03/07/2016 SH -9 5 SZ date city temperature wind 18 11/09/2016 SZ 20 1 19 25/09/2016 SZ -10 4 ''' #类似数据库的运算如下 select * from table_1 group by column_1

Aggregation 数据聚合

#导入库 import numpy as np import pandas as pd from pandas import Series, DataFrame #读取文件数据 df = pd.read_csv('../homework/city_weather.csv')

得到 。。。

#数据分组,得到分组数据 g =df.groupby('city') #数据的一般聚合,与分组直接得到结果一致 g.agg('min')

得到

#数据的函数聚合,可以定义一个函数进行操作 #最大值减最小值 def foo(attr): return attr.max() - attr.min() #使用函数进行聚合操作 g.agg(foo)

得到

#用两列进行数据分组 g_new = df.groupby(['city', 'wind']) ''' 得到 <pandas.core.groupby.DataFrameGroupBy object at 0x10f9c75c0> ''' #使用两个参数找到分组 g_new.get_group(('BJ',3))

得到

#使用一个参数也可以找到分组 g.get_group('BJ')

得到

#遍历两个参数的分组 for (name_1,name_2), group in g_new: print(name_1,name_2) print(group)

得到 BJ 2 date city temperature wind 1 17/01/2016 BJ 12 2 2 31/01/2016 BJ 19 2 4 28/02/2016 BJ 19 2 BJ 3 date city temperature wind 3 14/02/2016 BJ -3 3 5 13/03/2016 BJ 5 3 BJ 5 date city temperature wind 0 03/01/2016 BJ 8 5 GZ 2 date city temperature wind 14 17/07/2016 GZ 10 2 GZ 4 date city temperature wind 17 28/08/2016 GZ 25 4 GZ 5 date city temperature wind 15 31/07/2016 GZ -1 5 16 14/08/2016 GZ 1 5 SH 2 date city temperature wind 10 22/05/2016 SH 4 2 SH 3 date city temperature wind 7 10/04/2016 SH 19 3 8 24/04/2016 SH 20 3 9 08/05/2016 SH 17 3 SH 4 date city temperature wind 6 27/03/2016 SH -4 4 11 05/06/2016 SH -10 4 SH 5 date city temperature wind 12 19/06/2016 SH 0 5 13 03/07/2016 SH -9 5 SZ 1 date city temperature wind 18 11/09/2016 SZ 20 1 SZ 4 date city temperature wind 19 25/09/2016 SZ -10 4

透视表-分类汇总

#导入库 import numpy as np import pandas as pd from pandas import Series, DataFrame #从文件得到一个DataFrame df = pd.read_excel('../homework/sales-funnel.xlsx')

得到

#pivot_table的参数包括DataFrame名称,索引-以哪几列为基准进行汇总,前后需要有包含关系,数值-汇总哪几个数值,列名-以哪几列作为分类标准,空栏填充数,汇总方式(求和)默认为平均值 pd.pivot_table(df, index=['Manager','Rep'],values=['Price','Quantity'],columns=['Product'], fill_value=0, aggfunc='sum')

得到

分组和透视-方法汇总

#导入库 import numpy as np import pandas as pd from pandas import Series, DataFrame #从文件得到一个DataFrame df = pd.read_csv('../homework/usa_flights.csv') df.shape ''' 得到 (201664, 14) ''' df.head()

得到

df.tail()

得到

#获取延误时间最长top10的航空公司 #用哪个列排序,升序/降序(降序)筛选前十个数据,规定显示的行数 df.sort_values('arr_delay', ascending=False)[:10][['flight_date','unique_carrier','flight_num','origin','dest','arr_delay']]

得到

#计算延误和没有延误所占比例 #计算航班取消的数量 df['cancelled'].value_counts() ''' 得到 0 196873 1 4791 Name: cancelled, dtype: int64 ''' #筛选延误航班的数据,应用lambda表达式,选取数值大于0的 #增加一列 df['delayed'] = df['arr_delay'].apply(lambda x: x > 0) df.head()

得到

#对['delayed']行进行数据统计 delay_data = df['delayed'].value_counts() ''' 得到 False 103037 True 98627 Name: delayed, dtype: int64 ''' #使用数据进行结果计算 delay_data[1]/(delay_data[0] + delay_data[1]) ''' 得到 0.48906597112027927 ''' #每一个航空公司延误的情况 #数据分组航空公司和是否延误列 delay_group = df.groupby(['unique_carrier','delayed']) ''' 得到 <pandas.core.groupby.DataFrameGroupBy object at 0x10d7c16a0> ''' #group.size()得到的是一个多级Series,将Series转换为DataFrame df_delay = delay_group.size().unstack()

得到

#画图展示情况 import matplotlib.pyplot as plt df_delay.plot(kind='barh', stacked=True, figsize=[16,6], colormap='winter') ''' 得到 <matplotlib.axes._subplots.AxesSubplot at 0x118e99208> ''' plt.show()

得到

#透视表功能 #透视表的参数,以flight_date列为汇总依据,按照unique_carrier列分类,计算数据flight_num,计算计数量 flights_by_carrier = df.pivot_table(index='flight_date', columns='unique_carrier', values='flight_num', aggfunc='count') flights_by_carrier.head()

得到


最新回复(0)