[编程经验] Pandas入门(二)

时间:2022-05-08
本文章向大家介绍[编程经验] Pandas入门(二),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

上次介绍了Pandas的部分操作,包括创建Series,DataFrame以及基本索引,文件保存与读取等。今天我们介绍一下Pandas常用的其他功能。

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

import pandas as pd
import numpy as np

sample = 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 pd
import numpy as np

sample = pd.read_csv("sample.csv", header=None)
print sample.head()

"""
    0   1   2
0   6  40  24
1   5  24  56
2  59  21  44
3  58   4  25
4  83  74  58
"""

# 排序

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

## sort_index

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

import pandas as pd
sample = pd.read_csv("sample.csv", header=None)
sort_index_1 = sample.sort_index(by=1)
print sort_index_1
"""
   0   1   2
3  58   4  25
2  59  21  44
1   5  24  56
0   6  40  24
4  83  74  58

"""
sort_index_axis_1 = sample.sort_index(by=1, axis=1)
print sort_index_axis_1
"""
    0   1   2
0   6  40  24
1   5  24  56
2  59  21  44
3  58   4  25
4  83  74  58
"""

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

sort_index_ascend = sample.sort_index(by=1, ascending=False)
print sort_index_ascend
"""
    0   1   2
4  83  74  58
0   6  40  24
1   5  24  56
2  59  21  44
3  58   4  25
"""

##sort_values

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

import pandas as pd
sample = pd.read_csv("sample.csv", header=None)

sample_sort_value = sample.sort_values(by=1)
print sample_sort_value
print " - * - " * 5

sample_sort_axis = sample.sort_values(by=1, axis=1)
print sample_sort_axis
print " - * - " * 5
sort_value_ascend = sample.sort_values(by=1, ascending=False)
print sort_value_ascend
"""
    0   1   2
3  58   4  25
2  59  21  44
1   5  24  56
0   6  40  24
4  83  74  58
 - * -  - * -  - * -  - * -  - * - 
    0   1   2
0   6  40  24
1   5  24  56
2  59  21  44
3  58   4  25
4  83  74  58
 - * -  - * -  - * -  - * -  - * - 
    0   1   2
4  83  74  58
0   6  40  24
1   5  24  56
2  59  21  44
3  58   4  25

"""

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

import pandas as pd
sample = 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_max
4  83  74  58       83
2  59  21  44       59
3  58   4  25       58
1   5  24  56       56
0   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 pd
import numpy as np

df = pd.DataFrame(np.random.randn(3, 3))
print df
print 
df = df.applymap(lambda x: '%.2f' % x)
print df
"""
     0      1       2
0  0.776506 -0.605382  1.843036
1  0.522743  1.267487  1.288286
2  0.495450  0.583332 -0.590918

      0      1      2
0  0.78  -0.61   1.84
1  0.52   1.27   1.29
2  0.50   0.58  -0.59
"""
import pandas as pd
x = pd.Series([1, 2, 3], index=['one', 'two', 'three'])
print x
y = pd.Series(['foo', 'bar', 'baz'], index=[1, 2, 3])
print
print y
print
print x.map(y)
"""
one      1
two      2
three    3
dtype: int64

1    foo
2    bar
3    baz
dtype: object

one      foo
two      bar
three    baz
dtype: 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 pd

sample = pd.read_csv("sample.csv", header=None)
sample['key1'] = ['a', 'b', 'b', 'a', 'b']
print sample
print
grouped = sample[1].groupby(sample['key1'])
print grouped
print
print grouped.mean()
print
print grouped.max()
"""
    0   1   2 key1
0   6  40  24    a
1   5  24  56    b
2  59  21  44    b
3  58   4  25    a
4  83  74  58    b

<pandas.core.groupby.SeriesGroupBy object at 0x0000000005E2ED68>

key1
a    22.000000
b    39.666667
Name: 1, dtype: float64

key1
a    40
b    74
Name: 1, dtype: int64

"""

关于时间序列的内容还挺多的,下次单独讲一次吧。今天就先到这里了,祝大家玩的开心! 最后要说的一点是,了解了基础之后,重点是怎么灵活应用各种简单的功能进而实现复杂的数据清洗等任务。

==============End==============