10、Pandas 的数据结构、统计特性及数据读写

来源:互联网 发布:最新网络流行英语词汇 编辑:程序博客网 时间:2024/05/17 07:21

一、Pandas 的数据结构(Series, DataFrame)


0. NumPy 和 Pandas 的区别?

  • 简单的向量操作与 ndarray 的表现一致
  • Seriesndarray 不同的地方在于,Series 的操作默认是使用 index 的值进行对齐的,而不是相对位置
  • DataFramendarray 不同的地方在于,DataFrame 的列数据可以是不同的类型

1. Series

它是一种类似一维数组的对象(obj),由一组数据(各种numpy数据类型)以及一组与之相关的数据标签(即索引)组成。

a 、生成 Series 对象:pd.Series(data, index=index)

  • 通过 list 构建 Series 对象ser_obj = pd.Series(range(10))
  • 通过 dict 构建 Series 对象
    • d = {'a' : 0., 'b' : 1., 'c' : 2.}, ser_obj = pd.Series(d)
    • 若创建 Series 对象的时候不给定 index,那么 index 将使用 dict 的 key 排序之后的结果,此时可使用 key 来索引数据
  • 通过 标量值 构建 Series 对象
    • 此时 index 值必须被指定,得到一个值为 data 与 index 等长的 Series
    • pd.Series(5, index=[‘a’, ‘b’, ‘c’])

b、获取数据

  • 通过index属性获取Series 对象数据的索引:ser_obj.index # 返回 index 对象 RangeIndex
  • 通过values属性获取Series 对象数据所有的值:ser_obj.values # 返回 ndarray
  • 通过索引获取 Series 对象数据的单一或部分值
    • Series 对象默认的索引下表为数字(pos),可以在创建 Series 对象的时候指定index 的值(label),eg: ser_obj = pd.Series(range(3), index=['a', 'b', 'c']) ,我们称‘a’、’b’、’c’ 为索引的 label
    • 行索引:ser_obj[pos] or ser_obj[label]
    • 切片索引:ser_obj[0:2] or ser_obj[label0 : label2],注意:位置索引(pos)是不包含终止索引的,但按label索引时是包含终止索引的
    • 不连续索引:ser_obj[[pos0, pos2]],注意是两个中括号; ser_obj[[label0, label2]]
    • 布尔索引:ser_obj[ser_bool] # ser_bool 可以为条件表达式,只取出布尔值为真的元素的值

c、预览数据

  • 通过 head 方法查看 Series 对象最前面几行的数据(默认为5):ser_obj.head(n)
  • 通过 tail 方法查看Series 对象最后面几行的数据(默认为5):ser_obj.tail(n)

d、Name 属性

  • 设置Series 对象的名字:ser_obj.name = 'temp'
  • 设置Series 对象的索引列的名字:ser_obj.index.name = 'year'

2. DataFrame(DF)

它是 pandas 中的二维数据结构,可以看成一个 Excel 中的工作表,或者一个 SQL 表,或者一个存储 Series 对象的字典

a 、生成 DF 对象:pd.DataFrame(data, index, columns)

  • index 用于指定行的 label,columns 用于指定列的 label,如果不传入参数,那么它们将会使用默认的值(从 0 开始的数字序列代替)。
  • 通过 ndarray 构建 DF 对象array = np.random.randn(5, 4) df_obj = pd.DataFrame(array)
  • 通过 dict 构建 DF 对象
    • df_obj = pd.DataFrame(dict)
    • 若创建 DF 对象的时候不给定 index 和 columns,那么 index 将使用从 0 开始的数字序列代替,columns 将使用字典中的 key 代替,且数据会自动扩展(broadcast)

b、数据操作(增删改查)

  • 通过index属性获取 DF 对象数据的行索引:df_obj.index # 返回 index 对象
  • 通过columns属性获取 DF 对象数据的列索引:df_obj.columns # 返回 index 对象
  • 通过values属性获取 DF 对象数据所有的值:df_obj.values # 返回 ndarray
  • 函数应用:df.apply(f, axis=0) ,将函数应用到列上(按列统计) df.applymap(f), 将函数应用到每个数据上
  • 转置:df.T
  • 排序
    • df.sort_index() 按照索引值的大小排序
    • df.sort_values(by = 'label') 按照 label 下值得大小进行排序
  • 增加列数据:df_obj[new_col_idx] = Series_type_data
  • 删除列数据:del df_obj[col_idx]
  • 改变数据值:df_obj[index] = new_value
  • 查看数据值:
    • df_obj[col_label] or df_obj.col_label ,列索引,返回的是 Series 类型的数据
    • df_obj[[label0, label2]] or df_obj[[0, 2]] ,不连续索引,注意是两重小括号,返回的是 DataFrame 类型的数据

c、预览数据

  • 通过 head 方法查看 DF 对象最前面几行的数据(默认为5):ser_obj.head(n)
  • 通过 tail 方法查看DF 对象最后面几行的数据(默认为5):ser_obj.tail(n)

3. 索引操作总结

  • 标签索引:df_obj.loc[0:2, label] == df_obj[label][0:2]
  • 位置索引:df_obj.iloc[0:2, pos] == df[[pos]][0:2]
  • 混合索引:df_obj.ix[0:2, label/pos] # 先按标签索引尝试操作,再按位置索引尝试操作
  • 注意:
    • 标签的切片索引是包含末尾位置的,而位置索引不包含
    • DF 索引时可将其看作是 ndarray 操作

二、Pandas 统计计算和描述

axis=0 按列统计,axis=1 按行统计

这里写图片描述


三、Pandas CSV(Comma-Separated Values) 数据的读写

Pandas 提供了一些用于将表格型数据读取为DataFrame对象的函数,主要有pandas.read_csv(parameters)DataFrame.to_csv(parameters)

1. 读操作:pandas.read_csv(parameters)

  • df_obj = pd.read_csv('path/to/file_in.csv', usecols=['col_label1', 'col_label2']),返回DataFrame类型的数据,只取文件指定的两列
  • 显示数据的前n行(默认n=5):df_obj.head(n)
  • 显示数据的后n行(默认n=5):df_obj.tail(n)
  • 读操作常用参数:
# filepath_or_buffer 表示文件系统位置、URL、文件型对象的字符串# sep 分隔符,默认为',' 可使用正则表达式进行模糊匹配进行分割, eg: sep='\s+',匹配多个空白字符(包括空格、换行符、制表符等) # header 用作列名的行号,不指定该参数时,Pandas 会把第一行当作列名。若指定 header=None, Pandas 就不会把第一行当作列名了,它会为数据重新分配位置参数序列(pos=0,1,...n)作为列名# namesarray-like, default None,list of column names to use. 用列表来指定列名,通常结合 header=None 使用# nrowsNumber of rows of file to read(只读取文件的几行,也可以用 DataFrame 的head() 或 tail() 方法实现). Useful for reading pieces of large files# usecolsAll elements in this array must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in names or inferred from the document header row(s). Eg:a valid usecols parameter would be [0, 1, 2] or [‘foo’, ‘bar’, ‘baz’]# skiprowsLine numbers to skip(用 list 指定想要跳过的行号即可 ) or number of lines to skip (int) at the start of the file# skipfooterNumber of lines at bottom of file to skip # chunksizeReturn TextFileReader object for iteration# encodingEncoding to use for UTF when reading/writing (ex. ‘utf-8’). List of Python standard encodings

2. 写操作:DataFrame.to_csv(parameters)

  • df_obj.to_csv('path/to/file_out.csv', index=None/False, header=None/False),把行标签去掉和列标签去掉
  • 写操作常用参数:
# path_or_buf文件保存路径# indexboolean, default True,Write row names (index)# headerboolean or list of string, default True,Write out column names. If a list of string is given it is assumed to be aliases for the column names# sep 分隔符,默认为',' # columnssequence, Columns to write(可以只保存一部分数据,通过指定列表来完成)# encoding A string representing the encoding to use in the output file, defaults to ‘ascii’ on Python 2 and ‘utf-8on Python 3

四、参考资料

1、10 Minutes to pandas
2、十分钟搞定pandas

0 0
原创粉丝点击