pandas之Series和Dataframe简单介绍
https://apachecn.github.io/pandas-doc-zh/
做笔记永远都是一个好习惯。俗话说:好记性不胜个烂笔头。大家看书的时候,是不是总有种感受,即使当时感觉理解了、记住了,隔几天就会忘记吧(呵呵,也可能是我太笨)。不管怎么说,随着我们看的书,学的技术(我专业计算机)越来越多,知识点也会零零散散的一大堆,当我们在以后的生活、工作中,需要用到以前学的知识时,会感觉它熟悉又陌生,这个时候我们就不得不翻出以前的书或者百度一下,Google一下,去寻找以前的记忆。网上的东西总是多而杂,有的时候找了半天都没有找到自己需要的。如果我们学习的时候有做笔记的习惯,这个时候我们只需要拿出自己的笔记或者再百度一下,看一看,再熟悉一下当时的感受,不仅把知识拿出来用,而且又加深了印象,多好的事。
我以前也想着看书的时候做做笔记,但是总是坚持不长时间,可能以前习惯用纸质的笔记本做笔记吧,自己的字又写的丑,所以写着写着自己就看不下去了吧,放弃了。总之,不管是用纸质的笔记本也好,电子的也好,记笔记总归是个好事。废话那么多,一是记录自己现在的想法,二是激励自己好好学习。
小车不倒继续推。下面我就书归正传。继续记录自己今天的学习。
pandas是构建于numpy之上的数据分析库,它使数据分析变的更简单。
pandas有两个主要的数据结构:Series and DataFrame 。
Series 是一个类似于一维数组的对象,它有一个数组标签,也称之为索引 (index)。
DataFrame 类似于一个表格,It has both a row and column index
创建Series:
In [2]: import pandas as pd # 首先导入 pandas 工具包,没有的话就下载喽 In [3]: obj = pd.Series([4,7,-2,8]) # 创建一个简单的 Series 对象 In [8]: obj1 = pd.Series([4,7,-2,8],index=['d','b','c','a']) # 创建带 index 的 Series 对象 # index 也可以这样写: index=list('dbca')
In [16]: sdata = {'Ohio': 35000, 'Texas': 71000, 'Oregon',: 16000, 'Utah': 5000}
In [18]: obj2 = pd.Series(sdata) # 通过 python 的 dict 创建 Series 对象,虽然 sdata 中带的 key
# 可用作 index, 但是在创建的时候也可再指定 index
Series 的两个属性:values and index
In [5]: obj.index Out[5]: RangeIndex(start=0, stop=4, step=1) # 这个是系统自动帮我们生成的,因为在上面我们并没有指定obj的 index, In [6]: obj.values Out[6]: array([ 4, 7, -2, 8], dtype=int64) In [12]: obj1.index # obj1 的 index Out[12]: Index(['d', 'b', 'c', 'a'], dtype='object')
Series 的操作:
索引操作: In [11]: obj1['a'] In [12]: obj1['d'] = 6 In [13]: obj1[['c', 'a', 'd']] In [15]: obj2[obj2 > 0] 数学运算: In [16]: obj1 * 2 In [17]: np.exp(obj1) 也可把 Series 当做一个 dict(本来也就是 key :value 的形式): In [18]: 'b' in obj1 Out[18]: True In [19]: 'e' in obj1 Out[19]: False 内置或者 Series 对象的方法: isnull and notnull, 判断 Series 的值是否为 NA In [21]: states = ['California', 'Ohio', 'Oregon', 'Texas'] In [22]: obj3 = pd.Series(sdata,index=states) In [23]: obj3 Out[23]: California NaN Ohio 35000.0 Oregon 16000.0 Texas 71000.0 dtype: float64 In [26]: pd.isnull(obj3) In [27]: pd.notnull(obj3) In [28]: obj3.isnull() 在两个 Series 做数学运算时,它会自动识别相同的 index : In [27]: obj2 + obj3 Out[27]: California NaN Ohio 70000.0 Oregon 32000.0 Texas 142000.0 Utah NaN dtype: float64
创建DataFrame:
In [28]: data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'], ...: 'year': [2000, 2001, 2002, 2001, 2002], ...: 'pop': [1.5, 1.7, 3.6, 2.4, 2.9]} In [29]: frame = pd.DataFrame(data) In [30]: frame Out[30]: pop state year 0 1.5 Ohio 2000 1 1.7 Ohio 2001 2 3.6 Ohio 2002 3 2.4 Nevada 2001 4 2.9 Nevada 2002 In [31]: frame = pd.DataFrame(data,columns=['year', 'state', 'pop']) # 自己指定 column 的值
如果创建的时候指定的 columns 没有对应的值,其值则会用 NA 填充:
In [35]: frame2 = pd.DataFrame(data, columns=['year', 'state', 'pop', 'debt'],
...: index=['one', 'two', 'three', 'four', 'five'])
In [36]: frame2Out[36]:
year state pop debt
one 2000 Ohio 1.5 NaN
two 2001 Ohio 1.7 NaN
three 2002 Ohio 3.6 NaN
four 2001 Nevada 2.4 NaN
five 2002 Nevada 2.9 NaN
嵌套的 dict 当做数据传递给 Dataframe,会把外层的 key 解析成列,而内层 key 的解析为行,
当然你也可以自己指定行 index ( DataFrame(pop, index=[2001, 2002, 2003]) )
In [57]: pop = {'Nevada': {2001: 2.4, 2002: 2.9}, ....: 'Ohio': {2000: 1.5, 2001: 1.7, 2002: 3.6}} indices:In [58]: frame3 = DataFrame(pop) In [59]: frame3 # 转置也可以 frame3.T Out[59]: Nevada Ohio 2000 NaN 1.5 2001 2.4 1.7 2002 2.9 3.6
其他的方式也可以创建Dataframe:
In [62]: pdata = {'Ohio': frame3['Ohio'][:-1], ....: 'Nevada': frame3['Nevada'][:2]} In [63]: DataFrame(pdata) Out[63]: Nevada Ohio 2000 NaN 1.5 2001 2.4 1.7
传递给 Dataframe 的参数可以是一下列表中的任意:
索引:
可以使用 dict 的方式获取某列的值,也可以以属性的方式获取:
In [37]: frame2['state'] Out[37]: one Ohio two Ohio three Ohio four Nevada five Nevada Name: state, dtype: object In [38]: frame2.year Out[38]: one 2000 two 2001 three 2002 four 2001 five 2002 Name: year, dtype: int64
获取某一行的值可以用 .ix (不推荐),或 .loc for label based indexing , .iloc for positional indexing
In [42]: frame2.loc['one'] # frame2.iloc[1]
Out[42]:
year 2000
state Ohio
pop 1.5
debt NaN
Name: one, dtype: object
也可以为行列索引指定名字:
In [64]: frame3.index.name = 'year'; frame3.columns.name = 'state' In [65]: frame3 Out[65]: state Nevada Ohio year 2000 NaN 1.5 2001 2.4 1.7 2002 2.9 3.6
赋值:
给某列赋值: In [46]: frame2['debt'] = 16.5 In [48]: frame2['debt'] = np.arange(5.) In [50]: val = Series([-1.2, -1.5, -1.7], index=['two', 'four', 'five']) In [51]: frame2['debt'] = val
给某个不存在的列赋值将产生一个新的列:
In [53]: frame2['eastern'] = frame2.state == 'Ohio'
用 del 删除某列:
In [55]: del frame2['eastern']
Index objects
索引是 Series 和 Dataframe 的重要属性。
创建 Series 和 DataFrame 时都可以指定标签:
In [68]: obj = Series(range(3), index=['a', 'b', 'c']) In [69]: index = obj.index In [70]: index Out[70]: Index([a, b, c], dtype=object) In [71]: index[1:] Out[71]: Index([b, c], dtype=object)
索引值不可以修改,例如:index[1] = 'd' 就会出错,这样可以保证数据之间安全的共享 index,但是我们可以 reindex(后面会提到)
下面是pandas中主要的索引对象:
index 的 in 操作:
In [77]: 'Ohio' in frame3.columns Out[77]: True In [78]: 2003 in frame3.index Out[78]: False
Table 5-3. Index methods and properties
Method Descriptionappend | Concatenate with additional Index objects, producing a new Index |
diff | Compute set difference as an Index |
intersection | Compute set intersection |
union | Compute set union |
isin | Compute boolean array indicating whether each value is contained in the passed collection |
delete | Compute new Index with element at index i deleted |
drop | Compute new index by deleting passed values |
insert | Compute new Index by inserting element at index i |
is_monotonic | Returns True if each element is greater than or equal to the previous element |
is_unique | Returns True if the Index has no duplicate values |
unique | Compute the array of unique values in the Index |