在了解了pandas数据结构之后,我们来了解一下pandas的统计功能,数据的迭代,排序等

一、pandas描述统计

    通过pandas来计算DataFrame上的描述性统计信息。比如计算求和sum(), 平均值mean(),标准差std()等。

import pandas as pdimport numpy as np
data = {'Name':pd.Series(['AI','BI','CI','DI','EI','FI','GI','HI','II','JI','KI','LI']), 'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]), 'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])}df = pd.DataFrame(data)# print(df)
# sum求和,行进行求和, axis=0(默认为)print('行求和:\n',df.sum())print('列求和:\n',df.sum(1)) # 列求和print('均值:\n',df.mean()) # 求均值print('标准差:\n',df.std()) # 求标准差print('中间值:\n',df.median()) # 求中间值print('最大值:\n',df.max()) # 求最大值print('最小值:\n',df.max()) # 求最小值"""运行结果:行求和: Age 382Name AIBICIDIEIFIGIHIIIJIKILIRating 44.92dtype: object列求和: 0 29.231 29.242 28.983 25.564 33.205 33.606 26.807 37.788 42.989 34.8010 55.1011 49.65dtype: float64均值: Age 31.833333Rating 3.743333dtype: float64标准差: Age 9.232682Rating 0.661628dtype: float64中间值: Age 29.50Rating 3.79dtype: float64最大值: Age 51Name LIRating 4.8dtype: object最小值: Age 51Name LIRating 4.8dtype: object"""

使用函数describe()进行数据汇总:

# 数据汇总data = {'Name':pd.Series(['AI','BI','CI','DI','EI','FI','GI','HI','II','JI','KI','LI']),     'Age':pd.Series([25,26,25,23,30,29,23,34,40,30,51,46]),   'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8,3.78,2.98,4.80,4.10,3.65])}df = pd.DataFrame(data)df.describe() # 图一df.describe(include='all')  # 图二

运行结果:

数据分析 ——— pandas基础(二)_python    数据分析 ——— pandas基础(二)_python_02

使用describe()函数进行数据汇总时,会将字符串类型的数据略去,include='all'汇总所有数据。

二、pandas迭代数据

    对Pandas对象进行基本迭代的行为取决于类型。在遍历一个Series时,它被视为类似数组,并且基本迭代产生这些值。其他数据结构(如DataFrame和Panel)遵循 类似于字典的 惯例,即迭代对象的键 。

1)迭代dataframe会给出列名:

# 迭代DataFrameimport pandas as pdimport numpy as npN=20df = pd.DataFrame({    'A': pd.date_range(start='2016-01-01',periods=N,freq='D'),    'x': np.linspace(0,stop=N-1,num=N),    'y': np.random.rand(N),    'C': np.random.choice(['Low','Medium','High'],N).tolist(),    'D': np.random.normal(100, 10, size=(N)).tolist()    })# print(df)# 在迭代时迭代的是列名称for col in df:    print(col)
"""输出: A C D x y0 2016-01-01 Medium 88.740476 0.0 0.2815251 2016-01-02 Medium 92.061160 1.0 0.1483442 2016-01-03 High 93.057051 2.0 0.1554063 2016-01-04 High 108.589210 3.0 0.0814654 2016-01-05 High 95.277005 4.0 0.517087迭代之后:ACDxy"""

2)df.iteritems()每列作为关键字进行迭代

df =  pd.DataFrame(np.random.randn(4,3), columns=['col1','col2','col3'])# print(df,'\n')for key, value in df.iteritems():    print(key, value)    """输出:col1 0   -0.2890471   -0.3204162    0.6853043   -0.807813Name: col1, dtype: float64col2 0    0.5924111   -0.3381102    1.1036853    1.122862Name: col2, dtype: float64col3 0   -0.3485561   -0.4925902    0.8849273    0.935640Name: col3, dtype: float64"""

3)df.iterrows()迭代每行数据

# iterrows()返回产生每个索引值的迭代器,以及包含每行数据的序列df =  pd.DataFrame(np.random.randn(4,3), columns=['col1','col2','col3'])# print(df,'\n')for row_index, row in df.iterrows():    print(row_index, row)"""输出:0 col1   -0.087832col2   -1.324081col3    1.313132Name: 0, dtype: float641 col1    0.329817col2    0.342322col3    1.289371Name: 1, dtype: float642 col1   -0.053737col2    0.161058col3    0.523620Name: 2, dtype: float643 col1   -1.178437col2    1.218258col3   -1.160780Name: 3, dtype: float64"""   

4) df.itertuples()

# itertuples()方法将返回一个迭代器df =  pd.DataFrame(np.random.randn(4,3), columns=['col1','col2','col3'])# print(df,'\n')for row in df.itertuples():    print(row)"""输出:Pandas(Index=0, col1=0.5457537018288817, col2=-0.37401151450088643, col3=-2.235913835211911)Pandas(Index=1, col1=-1.4238446924342996, col2=-0.4261995350415312, col3=0.08808519885568705)Pandas(Index=2, col1=0.11412449447969304, col2=0.08229900426917722, col3=1.2282534332216126)Pandas(Index=3, col1=0.20299122204228656, col2=-0.9408608550972959, col3=-1.1829619921986732)"""

三、pandas进行排序

pandas有两种排序方式:按标签,按照实际值排序

1)按照标签排序:

    使用 sort_index()方法,通过传递轴参数和排序顺序,可以对DataFrame进行排序。

默认情况下,按行标签按升序排序。

df=pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns=['col2','col1'])# 按照标签排序sorted_index = df.sort_index()print(sorted_index)# ascending设置排序顺序sorted_index1 = df.sort_index(ascending=False)  # 逆序 print(sorted_index1)"""输出:       col2      col10 -0.262209 -1.0079281 -0.763948  0.4379402  0.805323 -0.6585543  0.913086  0.5138684 -1.719606  0.3194435 -0.324522  0.6586916  0.864936  0.8662457  1.719902  0.8225768  0.202719  0.0627389 -0.490119  0.028284
col2 col19 -0.490119 0.0282848 0.202719 0.0627387 1.719902 0.8225766 0.864936 0.8662455 -0.324522 0.6586914 -1.719606 0.3194433 0.913086 0.5138682 0.805323 -0.6585541 -0.763948 0.437940"""

2)对列进行排序

    通过传递值为0或1的轴参数,可以在列标签上完成排序。默认情况下,axis = 0,按行排序。

df=pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns=['col2','col1'])print(df)# 对列进行排序sorted_df_co = df.sort_index(axis=1)print(sorted_df_co)"""输出:       col2      col11 -2.032845 -1.4346634  1.457698  1.1569296 -1.892306  0.2160952 -0.765713  0.4773623 -0.662442  1.2671985  1.408257 -0.2480569  1.919813  0.3167568 -1.677476  1.1918250 -0.054794 -1.0045667  0.940486  0.565741
col1 col21 -1.434663 -2.0328454 1.156929 1.4576986 0.216095 -1.8923062 0.477362 -0.7657133 1.267198 -0.6624425 -0.248056 1.4082579 0.316756 1.9198138 1.191825 -1.6774760 -1.004566 -0.0547947 0.565741 0.940486"""

3)按值排序

    像索引排序一样,sort_value()是按值排序的方法。它接受一个'by'参数,该参数将使用DataFrame的列名与值进行排序。

# 按照值排序unsorted_df = pd.DataFrame({'col1':[2,1,1,1],'col2':[1,3,2,4]})sorted_df = unsorted_df.sort_values(by='col1') print(sorted_df)"""输出:   col1  col21     1     32     1     23     1     40     2     1"""
# 通过参数by进行列值排序unsorted_df = pd.DataFrame({'col1':[2,1,1,1],'col2':[1,3,2,4]})sorted_df = unsorted_df.sort_values(by=['col1','col2'])print(sorted_df)"""输出:   col1  col22     1     21     1     33     1     40     2     1"""

4)排序算法

    sort_value() 提供了一个从mergesort,heapsort和quicksort中选择算法的规定。Mergesort是唯一稳定的算法。

# mergesort排序算法unsorted_df = pd.DataFrame({'col1':[2,1,1,1],'col2':[1,3,2,4]})sorted_df = unsorted_df.sort_values(by='col1', kind='mergesort')
print(sorted_df)"""输出: col1 col21 1 32 1 23 1 40 2 1"""


数据分析 ——— pandas基础(二)_python_03


数据分析 ——— pandas基础(二)_python_04机器学习&深度学习&人工智能资料
python基础资料数据分析资料数据分析 ——— pandas数据结构(一)
数据分析 —numpy基础(三)所有爬虫文章的归类

数据分析 ——— pandas基础(二)_python_05