当前位置: 移动技术网 > IT编程>脚本编程>Python > Python数据分析实战之Pandas库简介

Python数据分析实战之Pandas库简介

2018年03月22日  | 移动技术网IT编程  | 我要评论

王的大牌特工妃全文免费阅读,恐怖宠物店下载,冥神录

1.Index对象

Pandas的Series和DataFrame数据结构,它们在数据分析方面的大多数优秀特性都取决于完全整合到这些数据结构中的Index对象。

跟pandas数据结构中其他元素不同的是,Index对象不可改变。声明后,它不能改变。不同数据结构共用Index对象时,该特性能够保证它的安全。

Index对象的方法:

idxmin()和idxmax()函数分别返回索引值最小和最大的元素。

ser = pd.Series([5,0,3,8,4],index=['red','blue','yellow','white','green'])
#返回索引最小的元素
ser.idxmin()
>> 'blue'
ser.idxmax()
>> 'white'

含有重复标签的Index:

Pandas数据结构允许存在重复的索引。

ser = pd.Series(range(6),index=['white','white','blue','green','green','yellow'])
serd
>>
white     0
white     1
blue      2
green     3
green     4
yellow    5
dtype: int32

从上述数据结构中选取元素时,如果一个标签对应多个元素,我们得到的将是一个Series对象而不是单个元素。

ser['white']
>>
white    0
white    1
dtype: int32

pandas的Index对象还有is_unique属性。调用该属性,就可以知道数据结构中是否存在重复的索引项。

ser.index.is_unique
>>
False

2.索引对象的其他功能

Python常用数据结构相比,pandas不仅利用了Numpy数组的高性能优势,还整合了索引机制。

索引对象的其他功能:更换索引、删除、对齐。

更换索引:

Index对象就不能改变,但是可以执行更换索引操作。

ser = pd.Series([2,5,7,4],index=['one','two','three','four'])
ser
>>
one      2
two      5
three    7
four     4
dtype: int64

pandas的reindex()函数可更换Series对象的索引。它根据新标签序列,重新调整原Series的元素,生成一个新的Series对象。
更换索引时,可以调整索引序列中各标签的顺序,删除或增加新标签。如增加新标签,pandas会添加NaN作为其元素。

ser.reindex(['three','four','five','one'])
ser
>>
three    7.0
four     4.0
five     NaN
one      2.0
dtype: float64

从返回结果可以看到,元素数值不变,标签顺序全部调整过。删除了标签two及其元素,增加了新标签five。

重新编制索引,定义所有的标签序列可能会很麻烦,对大型DataFrame来说更是如此。但是我们可以使用自动填充或插值方法。

ser = pd.Series([1,5,6,3],index=[0,3,5,6])
ser
>>
0   1
3   5
5   6
6   3

#需要指定索引值的范围。要指定一列0-5的值,参数为range(6)
ser.reindex(np.arange(6),method='ffill')
>>
0    1
1    1
2    1
3    5
4    5
5    6
dtype: int64

ser.reindex(np.arange(6),method='bfill')
>>
0    1
1    5
2    5
3    5
4    6
5    6
dtype: int64

method参数为ffill时是插入项的值为前面索引编号比它小的那一项元素。为bfill时是插入后面索引编号比它大的那一项元素。

更换索引的概念可以由Series扩展到DataFrame,你不仅可以更换索引(行),还可以更换列,甚至更换两者。pandas会用NaN弥补原数据结构中缺失的元素。

frame.reindex(range(5),method='ffill',columns=['colors','price','new','object'])
>>
    colors   price   new   object
0   blue      1.2    NaN   ballpand
1   green     1.0    NaN   pen
2   yellow    0.6    NaN   pencil
3   red       0.9    NaN   paper
4   white     1.7    NaN   mug

删除索引:

因为索引和列名称有了标签作为标识,所以删除操作变得很简单。

pandas专门提供了一个用于删除操作的函数:drop(),它返回不包含已删除索引及其元素的新对象。

ser = pd.Series(np.arange(6),index=['a','b','c','d','e','f'])
ser
>>
a    0
b    1
c    2
d    3
e    4
f    5
dtype: int32

#删除某一项或多项
ser.drop('a')
ser.drop(['a','b'])

DataFrame数据结构中删除元素,需要指定元素两个轴的轴标签。

frame = pd.DataFrame(
    np.arange(16).reshape(4,4),
    index = ['red','blue','yellow','white'],
    columns = ['ball','pen','pencil','paper']
) 
frame
>>
        ball   pen   pencil   paper
red     0       1       2       3
blue    4       5       6       7
yellow  8       9       10      11
white   12      13      14      15

#1.DataFrame结构,删除一行时传入行的索引即可
frame.drop(['blue','yellow'])
>>
        ball   pen   pencil   paper
red     0       1       2       3
white   12      13      14      15

#2.DataFrame结构,删除一列时传入列的索引,同时还要指定axis为1
frame.drop(['pen','pencil'],axis=1)
>>
        Ball   paper
red     0       3
blue    4       7
yellow  8       11

即对于DataFrame数据结构,删除行只需要传入索引即可,删除列的话传入索引同时还要指定axis=1参数。

3.算术和数据对齐

Pandas很擅长对齐不同数据结构的索引项。

#Series对象
s1 = pd.Series([3,2,5,1],index=['white','yellow','green','blue']) 
s2 = pd.Series([1,4,7,2,1],index=['white','yellow','black','blue','bron']) 
s1+s2
>>
black   NaN
blue    3
brown   NaN
green   NaN
white   4
yellow  6
dtype: float64
#DataFrame对象
frame = pd.DataFrame(
    np.arange(16).reshape((4,4)),
    index = ['red','blue','yellow','white'],
    columns = ['ball','pen','pencil','paper']
) 
frame2 = pd.DataFrame(
    np.arange(12).reshape((4,3)),
    index = ['blue','green','white','yellow'],
    columns = ['mug','pen','ball']
)

frame + frame2
        ball    mug paper   pen    pencil
blue    6.0     NaN NaN     6.0    NaN
green   NaN     NaN NaN     NaN    NaN
red     NaN     NaN NaN     NaN    NaN
white   20.0    NaN NaN     20.0   NaN
yellow  19.0    NaN NaN     19.0   NaN

4.数据结构之间的运算

灵活的算术运算方法:

前面刚学过可直接在Pandas数据结构之间使用算术运算符。相同的运算还可以借助灵活的算术运算方法来完成。

加减乘除:add()、sub()、p()、mul()

df1 = pd.DataFrame(
    np.arange(4).reshape(2,2),
    columns = ['a','b'],
    index = ['one','two']
)
df1
>>
    a   b
one 0   1
two 2   3

df2 = pd.DataFrame(
    np.arange(10,19).reshape(3,3),
    columns = ['a','b','c'],
    index = ['one','two','three']
)
df2
>>
        a   b   c
one     10  11  12
two     13  14  15
three   16  17  18

#1.add() 分别尝试不填充和填充
df1.add(df2)
>>
         a     b     c
one     10.0   12.0  NaN
three   NaN    NaN   NaN
two     15.0   17.0  NaN

df1.add(df2,fill_value=0)
>>
        a       b       c
one     10.0    12.0    12.0
three   16.0    17.0    18.0
two     15.0    17.0    15.0

#2.sub()
df1.sub(df2)
>>
            a     b     c
one     -10.0   -10.0   NaN
three   NaN     NaN     NaN
two     -11.0   -11.0   NaN

#3.p()
df1.p(df2)
>>
            a         b          c
one     0.000000    0.090909    NaN
three   NaN         NaN         NaN
two     0.153846    0.214286    NaN

#4.mul()
df1.mul(df2)
>>
        a       b       c
one     0.0     11.0    NaN
three   NaN     NaN     NaN
two     26.0    42.0    NaN

sub()、p()、mul()也可以用fill_value参数进行填充。

DataFrame和Series对象之间的运算:

Pandas允许DtaaFrame和Series数据结构间进行运算。

frame
>>
        ball   pen   pencil   paper
red     0       1       2       3
blue    4       5       6       7
yellow  8       9       10      11
white   12      13      14      15

ser
>>
ball    0
pen     1
pencil  2
paper   3
dtype: int32

frame - ser
>>
        ball   pen   pencil   paper
red     0       0       0       0
blue    4       4       4       4
yellow  8       8       8       8
white   12      12      12      12

DataFrame对象各元素分别减去了Series对象中索引与之相同的元素。
如果一个索引只存在于其中一个数据结构之中,则运算结果中会为该索引项生成一列,只不过该列的所有元素都是NaN。

ser['mug'] = 9
ser
>>
ball    0
pen     1
pencil  2
paper   3
mug     9
dtype: int32

frame - ser
>>
        ball   mug   pen   pencil   paper
red     0      NaN    0     0       0
blue    4      NaN    4     4       4
yellow  8      NaN    8     8       8
white   12     NaN    12    12      12

5.函数应用和映射

这一节将讲解pandas库函数。

操作元素的函数:

pandas库以Numpy为基础,并对它的很多功能进行了扩展,以用来操作新数据结构Series和DataFrame。

通用函数就是经过扩展得到的功能,这类函数能够对数据结构中的元素进行操作,因此特别有用。

例如,使用np.sqrt()函数就能计算DataFrame对象每个元素的平方根。

frame
>>
        ball   pen   pencil   paper
red     0       1       2       3
blue    4       5       6       7
yellow  8       9       10      11
white   12      13      14      15

np.sqrt(frame)
>>
            ball    pen         pencil      paper
red     0.000000    1.000000    1.414214    1.732051
blue    2.000000    2.236068    2.449490    2.645751
yellow  2.828427    3.000000    3.162278    3.316625
white   3.464102    3.605551    3.741657    3.872983

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网