温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Pandas常用的功能有哪些

发布时间:2021-11-30 10:21:47 阅读:290 作者:小新 栏目:大数据
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

这篇文章主要介绍Pandas常用的功能有哪些,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

首先我们还是随机产生一个数据表,5行3列的数据框。保存到csv文件并读取。

import pandas as pdimport numpy as npsample = np.array(np.random.randint(0,100, size=15))sample_reshape = sample.reshape((5,3))sample_pd = pd.DataFrame(sample_reshape)sample_pd.to_csv("sample.csv",header=None, index=None)
import pandas as pdimport numpy as npsample = pd.read_csv("sample.csv", header=None)print sample.head()"""    0   1   20   6  40  241   5  24  562  59  21  443  58   4  254  83  74  58"""

# 排序

首先介绍一下如何对数据框进行排序,总的来说,pandas提供两种排序方法,一个是根据索引值排序,一个是根据数据框中某一列或者某一行排序,这个就和Excel中的排序是一样的,但是它排序的结果是扩展到整个数据表的,不是按照单独一行或者一列排序,如果要对行或者列单独排序,可以首先把行或者列索引出来,然后在排序。

## sort_index

by参数指定列名,axis默认为0, 桉列排序,排序之后得到4, 21, 24,40, 74,可以指定axis为1,按行排序, 结果为5, 24, 56。

import pandas as pdsample = pd.read_csv("sample.csv", header=None)sort_index_1 = sample.sort_index(by=1)print sort_index_1"""   0   1   23  58   4  252  59  21  441   5  24  560   6  40  244  83  74  58"""sort_index_axis_1 = sample.sort_index(by=1, axis=1)print sort_index_axis_1"""    0   1   20   6  40  241   5  24  562  59  21  443  58   4  254  83  74  58"""

ascending参数指定降序排序,由大到小。

sort_index_ascend = sample.sort_index(by=1, ascending=False)print sort_index_ascend"""    0   1   24  83  74  580   6  40  241   5  24  562  59  21  443  58   4  25"""

##sort_values

通过结果,我们发现sort_values和sort_index几乎是相同的。But, sort_index后面将会被弃用。。。所以大家也可以只学习sort_values的用法。

import pandas as pdsample = pd.read_csv("sample.csv", header=None)sample_sort_value = sample.sort_values(by=1)print sample_sort_valueprint " - * - " * 5sample_sort_axis = sample.sort_values(by=1, axis=1)print sample_sort_axisprint " - * - " * 5sort_value_ascend = sample.sort_values(by=1, ascending=False)print sort_value_ascend"""    0   1   23  58   4  252  59  21  441   5  24  560   6  40  244  83  74  58 - * -  - * -  - * -  - * -  - * -     0   1   20   6  40  241   5  24  562  59  21  443  58   4  254  83  74  58 - * -  - * -  - * -  - * -  - * -     0   1   24  83  74  580   6  40  241   5  24  562  59  21  443  58   4  25"""

下面我们看个稍微高级点的玩法,如果要按照某一行或者列的最大值来排序,该怎么做。首先我们新添加一列,用来求每一行的最大值。然后我们根据最大值降序排序就可以了。

import pandas as pdsample = pd.read_csv("sample.csv", header=None)sample['row_max'] = sample.apply(lambda x: x.max(), axis=1)new = sample.sort_values(by='row_max', ascending=False)print new """    0   1   2  row_max4  83  74  58       832  59  21  44       593  58   4  25       581   5  24  56       560   6  40  24       40"""

学会怎么按照最大值排序,那么按照其他统计量也就可以了,比如均值,最小值等等。

# apply, applymap, map

这三个函数中,前两个是针对DataFrame使用的, 而map是针对Series使用的。 首先看一下函数文档,也就基本清楚他们怎么用了。

DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)

DataFrame.applymap(func)

Series.map(arg, na_action=None)

apply函数是将一个函数func,应用到DataFrame的元素中,其中axis指定数据的维度,其他几个参数不常用,这里不说了, 然后大家有需要用的时候可以去看看。applymap是将函数func直接应用到每一个元素中;map函数是将值和某个Series对应起来,下面看个栗子。

import pandas as pdimport numpy as npdf = pd.DataFrame(np.random.randn(3, 3))print dfprint df = df.applymap(lambda x: '%.2f' % x)print df"""     0      1       20  0.776506 -0.605382  1.8430361  0.522743  1.267487  1.2882862  0.495450  0.583332 -0.590918      0      1      20  0.78  -0.61   1.841  0.52   1.27   1.292  0.50   0.58  -0.59"""
import pandas as pdx = pd.Series([1, 2, 3], index=['one', 'two', 'three'])print xy = pd.Series(['foo', 'bar', 'baz'], index=[1, 2, 3])printprint yprintprint x.map(y)"""one      1two      2three    3dtype: int641    foo2    bar3    bazdtype: objectone      footwo      barthree    bazdtype: object"""

# 分组

DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, **kwargs)

然后还是之前的数据,我们新添加一列,列名为key1,分组的意思就是将数据框以某种标志分为不同的组,这里选择key1作为分组依据,这样就分为了两组,分组的作用的我们可以分别统计各自组内的统计量。比如要分析不同性别,不同年龄段等等问题的时候,就会用到分组统计。

注意这里grouped是一个SeriesGroupBy 对象,具体统计的时候,需要用SeriesGroupBy 的方法。

import pandas as pdsample = pd.read_csv("sample.csv", header=None)sample['key1'] = ['a', 'b', 'b', 'a', 'b']print sampleprintgrouped = sample[1].groupby(sample['key1'])print groupedprintprint grouped.mean()printprint grouped.max()"""    0   1   2 key10   6  40  24    a1   5  24  56    b2  59  21  44    b3  58   4  25    a4  83  74  58    b<pandas.core.groupby.SeriesGroupBy object at 0x0000000005E2ED68>key1a    22.000000b    39.666667Name: 1, dtype: float64key1a    40b    74Name: 1, dtype: int64"""

以上是“Pandas常用的功能有哪些”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

原文链接:https://my.oschina.net/alvinpy/blog/4392256

AI

开发者交流群×