White Python Data Analysis School (5): Pandas (D) Basic Operation (1) Data View

Contribute to the country at home too boring, it is better to me to learn Python together

Life is short, I used Python

The foregoing Portal:

White school Python Data Analysis (1): Based on the analysis of data

White Python Data Analysis School (2): Pandas (a) Overview

White Python Data Analysis School (3): Pandas (ii) Data structure Series

White Python Data Analysis School (4): Pandas (iii) data structure DataFrame

introduction

Recently the series did not have time to update, reasons are not looking, just a little summary lazy! Too lazy to learn!

I was such a capable and found the courage to admit mistakes.

But from the beginning of this, I resumed the update manually look funny :)

Next, small series to share some of the underlying operating Pandas may be a little bored, but still hope for students who are interested can knock shining the code yourself.

Much gossip talk, let's start the topic.

View data

The contents of the previous two, we introduce two kinds of data structures Pandas herein, this content will focus on some of the search operation about DataFrame, after all, is the same DataFrame similar to a two-dimensional table data structure, we usually will be more more use DataFrame.

The first portion is introduced into the first and NumPy Pandas, and to generate a DataFrame, here small form simply using the random number is generated, as follows:

import numpy as np
import pandas as pd

dates = pd.date_range('20200101', periods=6)
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))

print(df)

Finally, we print here a bit this generated DataFrame, results are as follows:

                   A         B         C         D
2020-01-01  0.177499 -0.025693  0.182894 -1.123577
2020-01-02  1.067580  1.592576 -0.010205 -0.349342
2020-01-03  1.141218  1.032333  1.364477  0.851630
2020-01-04  0.920260 -0.243247  0.196369 -0.835655
2020-01-05 -0.729184 -0.235706  1.144007 -1.048619
2020-01-06 -0.480888 -0.995325 -0.283726  0.428644

Above our preparation work is complete, has built DataFrame a randomly generated, let's look at some simple values ​​operation.

The first is the first value from the head start, here is the method to use head(), for example, now need to remove the data in the first row above the df, then we can write:

# 查看头部数据
print(df.head(1))

The results are as follows:

                   A         B         C         D
2020-01-01  0.177499 -0.025693  0.182894 -1.123577

Since there is access from the head so there must be access from the tail, this method is tail(), as usage and above, here we remove the data from the two lines of the tail, as follows:

# 查看尾部数据
print(df.tail(2))

The results are as follows:

                   A         B         C         D
2020-01-05 -0.729184 -0.235706  1.144007 -1.048619
2020-01-06 -0.480888 -0.995325 -0.283726  0.428644

Df before the control point of view, you can see the computer successfully accomplished our goal.

接下来,我们获取这个 df 的索引,这里可以用到的方法是 index ,如下:

# 获取索引
print(df.index)

结果如下:

DatetimeIndex(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04',
               '2020-01-05', '2020-01-06'],
              dtype='datetime64[ns]', freq='D')

能获取索引那么就一定能获取所有的列名,这个方法大家可能都猜到了,就是 columns ,没毛病, Pandas 的命名还是很友好的,直接就是英文翻译,多的我这里就不吐槽了,命名不规范的代码经常性的会造成他人的误解,所以建议各位尽量命名规范一点:

# 获取列名
print(df.columns)

结果如下:

Index(['A', 'B', 'C', 'D'], dtype='object')

这里 Pandas 还为我们提供了一个很 NB 的方法,就是直接快速查看数据的统计摘要,这个方法是 describe() ,这个方法可以让我们简单的知道一个我们不清楚内容的 DataFrame 里面具体内容,如下:

# 查看数据的统计摘要
print(df.describe())

结果如下:

              A         B         C         D
count  6.000000  6.000000  6.000000  6.000000
mean   0.349414  0.187490  0.432303 -0.346153
std    0.818647  0.948383  0.663604  0.821275
min   -0.729184 -0.995325 -0.283726 -1.123577
25%   -0.316291 -0.241362  0.038070 -0.995378
50%    0.548879 -0.130700  0.189632 -0.592498
75%    1.030750  0.767826  0.907098  0.234148
max    1.141218  1.592576  1.364477  0.851630

这里的数据统计的挺全乎的,包括了数据量、均值、方差、最大值、最小值等。

小编这里邪恶的想,如果在上中学考试的时候有这玩意,就再也不需要用手在草稿纸上一个一个去做重复的体力劳动了。

Pandas 还为我们提供了一个神奇的功能,「转置数据」,就是把行列互换,示例如下:

# 转置数据
print(df.T)

结果如下:

   2020-01-01  2020-01-02  2020-01-03  2020-01-04  2020-01-05  2020-01-06
A    0.177499    1.067580    1.141218    0.920260   -0.729184   -0.480888
B   -0.025693    1.592576    1.032333   -0.243247   -0.235706   -0.995325
C    0.182894   -0.010205    1.364477    0.196369    1.144007   -0.283726
D   -1.123577   -0.349342    0.851630   -0.835655   -1.048619    0.428644

是不是很神奇,不过小编觉得并无什么实际用处。

我们在实际的应用场景中,经常会遇到排序的需求, Pandas 为我们提供了两个方法, sort_index()sort_values()

为了便于演示,小编这里重新构造了一个乱序的 DataFrame ,如下:

df1 = pd.DataFrame({'b' :[1,2,3,2],'a':[4,3,2,1],'c':[1,3,8,2]},index=[2,0,1,3])
print(df1)

结果如下:

   b  a  c
2  1  4  1
0  2  3  3
1  3  2  8
3  2  1  2

可以看到,这个 df1 从索引和列名上看顺序都是乱序的,接下来我们开始对这个 df1 进行排序,首先我们先使用 sort_values()

sort_values()

用途:既可以根据列数据,也可根据行数据排序。

注意:必须指定by参数,即必须指定哪几行或哪几列;无法根据 index 和 columns 排序(由 sort_index() 执行)

语法:DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last')

  • axis:{0 or ‘index’, 1 or ‘columns’}, default 0,默认按照列排序,即纵向排序;如果为1,则是横向排序。
  • by:str or list of str;如果axis=0,那么by="列名";如果axis=1,那么by="行名"。
  • ascending:布尔型,True则升序,如果by=['列名1','列名2'],则该参数可以是[True, False],即第一字段升序,第二个降序。
  • inplace:布尔型,是否用排序后的数据框替换现有的数据框。
  • kind:排序方法,{‘quicksort’, ‘mergesort’, ‘heapsort’}, default ‘quicksort’。似乎不用太关心。
  • na_position:{‘first’, ‘last’}, default ‘last’,默认缺失值排在最后面。

按 b 列升序排序:

# 按 b 列升序排序
print(df1.sort_values(by='b'))

结果如下:

   b  a  c
2  1  4  1
0  2  3  3
3  2  1  2
1  3  2  8

先按 b 列降序,再按 a 列升序排序:

# 先按 b 列降序,再按 a 列升序排序
print(df1.sort_values(by=['b','a'],axis=0,ascending=[False,True]))

结果如下:

   b  a  c
1  3  2  8
3  2  1  2
0  2  3  3
2  1  4  1

按行 3 升序排列,必须指定 axis = 1

# 按行 3 升序排列,必须指定 axis = 1
print(df1.sort_values(by=3,axis=1))

结果如下:

   a  b  c
2  4  1  1
0  3  2  3
1  2  3  8
3  1  2  2

按行 3 升序,行 0 降排列:

# 按行 3 升序,行 0 降排列
print(df1.sort_values(by=[3,0],axis=1,ascending=[True,False]))

结果如下:

   a  c  b
2  4  1  1
0  3  3  2
1  2  8  3
3  1  2  2

sort_index()

用途:默认根据行标签对所有行排序,或根据列标签对所有列排序,或根据指定某列或某几列对行排序。

注意:df.sort_index() 可以完成和 df.sort_values() 完全相同的功能,但 python 更推荐用只用 df.sort_index() 对 index 和 columns 排序,其他排序方式用 df.sort_values()

语法:DataFrame.sort_index(axis=0, level=None, ascending=True, inplace=False, kind='quicksort', na_position='last', sort_remaining=True, by=None)

  • axis:0 按照行名排序;1 按照列名排序。
  • level:默认 None ,否则按照给定的 level 顺序排列。
  • ascending:默认 True 升序排列; False 降序排列。
  • inplace:默认False,否则排序之后的数据直接替换原来的数据框。
  • kind:排序方法,{‘quicksort’, ‘mergesort’, ‘heapsort’}, default ‘quicksort’。似乎不用太关心。
  • na_position:缺失值默认排在最后{"first","last"}。
  • by:按照某一列或几列数据进行排序,但是by参数貌似不建议使用。

默认按「行标签」升序排列:

# 默认按「行标签」升序排列
print(df1.sort_index())

结果如下:

   b  a  c
0  2  3  3
1  3  2  8
2  1  4  1
3  2  1  2

按「列标签」升序排列:

# 按「列标签」升序排列
print(df1.sort_index(axis=1))

结果如下:

   a  b  c
2  4  1  1
0  3  2  3
1  2  3  8
3  1  2  2

还有两个按列排序的例子:

# 先按 b 列「降序」排列,因为 b 列中有相同值,相同值再按 a 列的「升序」排列
print(df1.sort_index(by=['b','a'],ascending=[False,True]))
# 先按 a 列「降序」排列,而 a 列中没有相同值,因此这里按 b 列的「升序」排列不起作用。
print(df1.sort_index(by=['a','b'],ascending=[False,True]))

结果如下:

   b  a  c
2  1  4  1
3  2  1  2
0  2  3  3
1  3  2  8
   b  a  c
2  1  4  1
0  2  3  3
1  3  2  8
3  2  1  2

虽然正常排序,但是程序运行后也出现了警告,如下:

FutureWarning: by argument to sort_index is deprecated, please use .sort_values(by=...)

这个警告的意思是不推荐我们使用 sort_index() 使用 by 这个参数,推荐我们使用 sort_values() 这个方法。

示例代码

老规矩,所有的示例代码都会上传至代码管理仓库 Github 和 Gitee 上,方便大家取用。

示例代码-Github

示例代码-Gitee

参考

https://www.pypandas.cn/docs/getting_started/10min.html

https://www.jianshu.com/p/f0ed06cd5003

Guess you like

Origin www.cnblogs.com/babycomeon/p/12329844.html