pandas 是基于 Numpy 构建的含有更高级数据结构和工具的数据分析包 类似于 Numpy 的核心是 ndarray,pandas 也是围绕着 Series 和 DataFrame 两个核心数据结构展开的 。Series 和 DataFrame 分别对应于一维的序列和二维的表结构。pandas 约定俗成的导入方法如下: from pandas import Series,DataFrameimport pandas as pd
SeriesSeries 可以看做一个定长的有序字典。基本任意的一维数据都可以用来构造 Series 对象: >>> s = Series([1,2,3.0,'abc'])>>> s0 11 22 33 abcdtype: object 虽然 Series 对象包含两个主要的属性:index 和 values,分别为上例中左右两列。因为传给构造器的是一个列表,所以 index 的值是从 0 起递增的整数,如果传入的是一个类字典的键值对结构,就会生成 index-value 对应的 Series;或者在初始化的时候以关键字参数显式指定一个 index 对象: >>> s = Series(data=[1,3,5,7],index = ['a','b','x','y'])>>> sa 1b 3x 5y 7dtype: int64>>> s.indexIndex(['a', 'b', 'x', 'y'], dtype='object')>>> s.valuesarray([1, 3, 5, 7], dtype=int64) Series 对象的元素会严格依照给出的 index 构建,这意味着:如果 data 参数是有键值对的,那么只有 index 中含有的键会被使用;以及如果 data 中缺少响应的键,即使给出 NaN 值,这个键也会被添加。 注意 Series 的 index 和 values 的元素之间虽然存在对应关系,但这与字典的映射不同。index 和 values 实际仍为互相独立的 ndarray 数组,因此 Series 对象的性能完全 ok。 Series 这种使用键值对的数据结构最大的好处在于,Series 间进行算术运算时,index 会自动对齐。 另外,Series 对象和它的 index 都含有一个 >>> s.name = 'a_series'>>> s.index.name = 'the_index'>>> sthe_indexa 1b 3x 5y 7Name: a_series, dtype: int64
DataFrameDataFrame 是一个表格型的数据结构,它含有一组有序的列(类似于 index),每列可以是不同的值类型(不像 ndarray 只能有一个 dtype)。基本上可以把 DataFrame 看成是共享同一个 index 的 Series 的集合。 DataFrame 的构造方法与 Series 类似,只不过可以同时接受多条一维数据源,每一条都会成为单独的一列: >>> data = {'state':['Ohino','Ohino','Ohino','Nevada','Nevada'], 'year':[2000,2001,2002,2001,2002], 'pop':[1.5,1.7,3.6,2.4,2.9]}>>> df = DataFrame(data)>>> df pop state year0 1.5 Ohino 20001 1.7 Ohino 20012 3.6 Ohino 20023 2.4 Nevada 20014 2.9 Nevada 2002[5 rows x 3 columns] 虽然参数 data 看起来是个字典,但字典的键并非充当 DataFrame 的 index 的角色,而是 Series 的 “name” 属性。这里生成的 index 仍是 “01234”。 较完整的 DataFrame 构造器参数为: >>> df = DataFrame(data,index=['one','two','three','four','five'], columns=['year','state','pop','debt'])>>> df year state pop debtone 2000 Ohino 1.5 NaNtwo 2001 Ohino 1.7 NaNthree 2002 Ohino 3.6 NaNfour 2001 Nevada 2.4 NaNfive 2002 Nevada 2.9 NaN[5 rows x 4 columns] 同样缺失值由 NaN 补上。看一下 index、columns 和 索引的类型: >>> df.indexIndex(['one', 'two', 'three', 'four', 'five'], dtype='object')>>> df.columnsIndex(['year', 'state', 'pop', 'debt'], dtype='object')>>> type(df['debt'])<class 'pandas.core.series.Series'> DataFrame 面向行和面向列的操作基本是平衡的,任意抽出一列都是 Series。 对象属性重新索引Series 对象的重新索引通过其 ser = Series([4.5,7.2,-5.3,3.6],index=['d','b','a','c'])>>> a = ['a','b','c','d','e']>>> ser.reindex(a)a -5.3b 7.2c 3.6d 4.5e NaNdtype: float64>>> ser.reindex(a,fill_value=0)a -5.3b 7.2c 3.6d 4.5e 0.0dtype: float64>>> ser.reindex(a,method='ffill')a -5.3b 7.2c 3.6d 4.5e 4.5dtype: float64>>> ser.reindex(a,fill_value=0,method='ffill')a -5.3b 7.2c 3.6d 4.5e 4.5dtype: float64
DataFrame 对象的重新索引方法为: >>> state = ['Texas','Utha','California']>>> df.reindex(columns=state,method='ffill') Texas Utha Californiaa 1 NaN 2c 4 NaN 5 d 7 NaN 8[3 rows x 3 columns]>>> df.reindex(index=['a','b','c','d'],columns=state,method='ffill') Texas Utha Californiaa 1 NaN 2b 1 NaN 2c 4 NaN 5d 7 NaN 8[4 rows x 3 columns] 不过 删除指定轴上的项即删除 Series 的元素或 DataFrame 的某一行(列)的意思,通过对象的 >>> serd 4.5b 7.2a -5.3c 3.6dtype: float64>>> df Ohio Texas Californiaa 0 1 2c 3 4 5d 6 7 8[3 rows x 3 columns]>>> ser.drop('c')d 4.5b 7.2a -5.3dtype: float64>>> df.drop('a') Ohio Texas Californiac 3 4 5d 6 7 8[2 rows x 3 columns]>>> df.drop(['Ohio','Texas'],axis=1) Californiaa 2c 5d 8[3 rows x 1 columns]
索引和切片就像 Numpy,pandas 也支持通过 不过须要注意,因为 pandas 对象的 index 不限于整数,所以当使用非整数作为切片索引时,它是末端包含的。 >>> fooa 4.5b 7.2c -5.3d 3.6dtype: float64>>> bar0 4.51 7.22 -5.33 3.6dtype: float64>>> foo[:2]a 4.5b 7.2dtype: float64>>> bar[:2]0 4.51 7.2dtype: float64>>> foo[:'c']a 4.5b 7.2c -5.3dtype: float64 这里 foo 和 bar 只有 index 不同——bar 的 index 是整数序列。可见当使用整数索引切片时,结果与 Python 列表或 Numpy 的默认状况相同;换成 另外一个特别之处在于 DataFrame 对象的索引方式,因为他有两个轴向(双重索引)。 可以这么理解:DataFrame 对象的标准切片语法为: >>> df Ohio Texas Californiaa 0 1 2c 3 4 5d 6 7 8[3 rows x 3 columns]>>> df.ix[:2,:2] Ohio Texasa 0 1c 3 4[2 rows x 2 columns]>>> df.ix['a','Ohio']0 而不使用 ix ,直接切的情况就特殊了:
这看起来有点不合逻辑,但作者解释说 “这种语法设定来源于实践”,我们信他。 >>> df['Ohio']a 0c 3d 6Name: Ohio, dtype: int32>>> df[:'c'] Ohio Texas Californiaa 0 1 2c 3 4 5[2 rows x 3 columns]>>> df[:2] Ohio Texas Californiaa 0 1 2c 3 4 5[2 rows x 3 columns] 使用布尔型数组的情况,注意行与列的不同切法(列切法的 >>> df['Texas']>=4a Falsec Trued TrueName: Texas, dtype: bool>>> df[df['Texas']>=4] Ohio Texas Californiac 3 4 5d 6 7 8[2 rows x 3 columns]>>> df.ix[:,df.ix['c']>=4] Texas Californiaa 1 2c 4 5d 7 8[3 rows x 2 columns]
算术运算和数据对齐pandas 最重要的一个功能是,它可以对不同索引的对象进行算术运算。在将对象相加时,结果的索引取索引对的并集。自动的数据对齐在不重叠的索引处引入空值,默认为 NaN。 >>> foo = Series({'a':1,'b':2})>>> fooa 1b 2dtype: int64>>> bar = Series({'b':3,'d':4})>>> barb 3d 4dtype: int64>>> foo + bara NaNb 5d NaNdtype: float64 DataFrame 的对齐操作会同时发生在行和列上。 当不希望在运算结果中出现 NA 值时,可以使用前面 reindex 中提到过 Series 和 DataFrame 之间的算术运算涉及广播,暂时先不讲。 函数应用和映射Numpy 的 ufuncs(元素级数组方法)也可用于操作 pandas 对象。 当希望将函数应用到 DataFrame 对象的某一行或列时,可以使用 f = lambda x:x.max()-x.min()>>> df Ohio Texas Californiaa 0 1 2c 3 4 5d 6 7 8[3 rows x 3 columns]>>> df.apply(f)Ohio 6Texas 6California 6dtype: int64>>> df.apply(f,axis=1)a 2c 2d 2dtype: int64
排序和排名Series 的 若要按值对 Series 进行排序,当使用 在 DataFrame 上, >>> df.sort_index(by='Ohio') Ohio Texas Californiaa 0 1 2c 3 4 5d 6 7 8[3 rows x 3 columns]>>> df.sort_index(by=['California','Texas']) Ohio Texas Californiaa 0 1 2c 3 4 5d 6 7 8[3 rows x 3 columns]>>> df.sort_index(axis=1) California Ohio Texasa 2 0 1c 5 3 4d 8 6 7[3 rows x 3 columns] 排名( >>> ser=Series([3,2,0,3],index=list('abcd'))>>> sera 3b 2c 0d 3dtype: int64>>> ser.rank()a 3.5b 2.0c 1.0d 3.5dtype: float64>>> ser.rank(method='min')a 3b 2c 1d 3dtype: float64>>> ser.rank(method='max')a 4b 2c 1d 4dtype: float64>>> ser.rank(method='first')a 3b 2c 1d 4dtype: float64 注意在 ser[0]=ser[3] 这对平级项上,不同 method 参数表现出的不同名次。 DataFrame 的 统计方法pandas 对象有一些统计方法。它们大部分都属于约简和汇总统计,用于从 Series 中提取单个值,或从 DataFrame 的行或列中提取一个 Series。 比如 >>> df one twoa 1.40 NaNb 7.10 -4.5c NaN NaNd 0.75 -1.3[4 rows x 2 columns]>>> df.mean()one 3.083333two -2.900000dtype: float64>>> df.mean(axis=1)a 1.400b 1.300c NaNd -0.275dtype: float64>>> df.mean(axis=1,skipna=False)a NaNb 1.300c NaNd -0.275dtype: float64 其他常用的统计方法有:
处理缺失数据pandas 中 NA 的主要表现为 np.nan,另外 Python 内建的 None 也会被当做 NA 处理。 处理 NA 的方法有四种: is(not)null这一对方法对对象做元素级应用,然后返回一个布尔型数组,一般可用于布尔型索引。 dropna对于一个 Series,dropna 返回一个仅含非空数据和索引值的 Series。 问题在于对 DataFrame 的处理方式,因为一旦 drop 的话,至少要丢掉一行(列)。这里的解决方式与前面类似,还是通过一个额外的参数: fillna
inplace 参数前面有个点一直没讲,结果整篇示例写下来发现还挺重要的。就是 Series 和 DataFrame 对象的方法中,凡是会对数组作出修改并返回一个新数组的,往往都有一个 |
|