pandas:数据分析

一、介绍

pandas是一个强大的Python数据分析的工具包,是基于NumPy构建的。

1.主要功能

具备对其功能的数据结构DataFrame、Series
集成时间序列功能
提供丰富的数学运算和操作
灵活处理缺失数据

2.安装方法

pip install pandas

3.引用方法

import pandas as pd

二、Series  

Series是一种类似于一位数组的对象,由一组数据和一组与之相关的数据标签(索引)组成。 

获取值数组和索引数组:values属性和index属性
Series比较像列表(数组)和字典的结合体。

创建方式:
    pd.Series([4,7,-5,3]) 
    pd.Series([4,7,-5,3],index=['a','b','c','d'])               
    pd.Series({'a':1, 'b':2})             
    pd.Series(0, index=['a','b','c','d’])

Series支持字典的特性(标签):

  • 从字典创建Series:Series(dic),
  • in运算:’a’ in sr、for x in sr
  • 键索引:sr['a'], sr[['a', 'b', 'd']]
  • 键切片:sr['a':'c']
  • 其他函数:get('a', default=0)等
In [12]: s = pd.Series(0,index=['a','b','c','d'])

In [13]: s.a
Out[13]: 0

In [14]: v = pd.Series({'a':1,'b':2})

In [15]: v.a
Out[15]: 1

In [16]: v.b
Out[16]: 2

In [17]: v[0]
Out[17]: 1

In [18]: s*2
Out[18]:
a    0
b    0
c    0
d    0
dtype: int64

In [19]: v*2
Out[19]:
a    2
b    4
dtype: int64  

三、整数索引 

整数索引的pandas对象往往会使新手抓狂。
例:

  • sr = np.Series(np.arange(4.))
  • sr[-1]

如果索引是整数类型,则根据整数进行数据操作时总是面向标签的。

    • loc属性 以标签解释
    • iloc属性 以下标解释

四、Series数据对齐

pandas在运算时,会按索引进行对齐然后计算。如果存在不同的索引,则结果的索引是两个操作数索引的并集。

    例:
    sr1 = pd.Series([12,23,34], index=['c','a','d'])
    sr2 = pd.Series([11,20,10], index=['d','c','a',])
    sr1+sr2
    sr3 = pd.Series([11,20,10,14], index=['d','c','a','b'])
    sr1+sr3

    如何在两个Series对象相加时将缺失值设为0?
    sr1.add(sr2, fill_value=0)
    灵活的算术方法:add, sub, div, mul

 

五、Series缺失数据

1、缺失数据:使用NaN(Not a Number)来表示缺失数据。其值等于np.nan。内置的None值也会被当做NaN处理。
2、处理缺失数据的相关方法:

  • dropna() 过滤掉值为NaN的行
  • fillna() 填充缺失数据
  • isnull() 返回布尔数组,缺失值对应为True
  • notnull() 返回布尔数组,缺失值对应为False

3、过滤缺失数据:sr.dropna() 或 sr[data.notnull()]
4、填充缺失数据:fillna(0)

六、DataFrame

DataFrame是一个表格型的数据结构,含有一组有序的列。
DataFrame可以被看做是由Series组成的字典,并且共用一个索引。

创建方式:

  • pd.DataFrame({'one':[1,2,3,4],'two':[4,3,2,1]})
  • pd.DataFrame({'one':pd.Series([1,2,3],index=['a','b','c']), 'two':pd.Series([1,2,3,4],index=['b','a','c','d'])})
  • ……

csv文件读取与写入:

    • df.read_csv('E:算法day110 Numpy、Pandas模块601318.csv')
    • df.to_csv()

七、DataFrame查看数据

查看数据常用属性及方法:
        index                    获取索引
        T                        转置
        columns                    获取列索引
        values                    获取值数组
        describe()                获取快速统计

    DataFrame各列name属性:列名
    rename(columns={})  

八、DataFrame索引和切片

DataFrame使用索引切片:
方法1:两个中括号,先取列再取行。    df['A'][0]
方法2(推荐):使用loc/iloc属性,一个中括号,逗号隔开,先取行再取列。
loc属性:解释为标签
iloc属性:解释为下标
向DataFrame对象中写入值时只使用方法2
行/列索引部分可以是常规索引、切片、布尔值索引、花式索引任意搭配。(注意:两部分都是花式索引时结果可能与预料的不同)
通过标签获取:
    df['A']
    df[['A', 'B']]
    df['A'][0]
    df[0:10][['A', 'C']]
    df.loc[:,['A','B']]  #行是所有的行,列取是A和B的
    df.loc[:,'A':'C']
    df.loc[0,'A']
    df.loc[0:10,['A','C']]
    
通过位置获取:
    df.iloc[3]
    df.iloc[3,3]
    df.iloc[0:3,4:6]
    df.iloc[1:5,:]
    df.iloc[[1,2,4],[0,3]]、
    
通过布尔值过滤:
  df[df['A']>0]
  df[df['A'].isin([1,3,5])]
  df[df<0] = 0 

九、DataFrame数据对齐与缺失数据

DataFrame对象在运算时,同样会进行数据对齐,行索引与列索引分别对齐。
结果的行索引与列索引分别为两个操作数的行索引与列索引的并集。

DataFrame处理缺失数据的相关方法:

    • dropna(axis=0,where=‘any’,…) 过滤掉值为NaN的行
    • fillna() 填充缺失数据
    • isnull() 返回布尔数组,缺失值对应为True
    • notnull() 返回布尔数组,缺失值对应为Fals
原文地址:https://www.cnblogs.com/moning/p/8379491.html