【pandas】[2] DataFrame 基础,创建DataFrame和增删改查基本操作(1)

作者:lianghc

地址:http://blog.****.net/zutsoft
        DataFrame 是pandas最常用的数据结构,类似于数据库中的表,不过DataFrame不仅仅限制于2维,可以创建多维数据表。DataFrame既有行索引,也有列索引,可以看做是Series组成的字典,每个Series看做DataFrame的一个列。

1.DataFrame创建:

1.标准格式创建
2.等长列表组成的字典来创建
3.嵌套字典(字典的值也是字典)创建

1.1  标准格式创建

 DataFrame创建方法有很多,常用基本格式是:DataFrame 构造器参数:DataFrame(data=[],index=[],coloumns=[])

[python] view plain copy
  1. In [272]: df2=DataFrame(np.arange(16).reshape((4,4)),index=['a','b','c','d'],columns=['one','two','three','four'])  
  2.   
  3. In [273]: df2  
  4. Out[273]:   
  5.    one  two  three  four  
  6. a    0    1      2     3  
  7. b    4    5      6     7  
  8. c    8    9     10    11  
  9. d   12   13     14    15  

1.2 用传入等长列表组成的字典来创建

[python] view plain copy
  1. In [204]: data={'c':['1','2'],'a':['5']}  #创建不等长字典序列  
  2.   
  3. In [205]: data  
  4. Out[205]: {'a': ['5'], 'c': ['1''2']}  
  5.   
  6. In [206]: df=DataFrame(data)  
  7. Traceback (most recent call last):  
  8. ...  
  9.   
  10. ValueError: arrays must all be same length   # 报错,传入的数组必须等长  
  11.   
  12. In [207]: data={'c':['1','2'],'a':['5','6']}  #创建<strong>等长字典序列  
  13. In [208]: df=DataFrame(data)  
  14.   
  15. In [209]: df  
  16. Out[209]:   
  17.    a  c                      # 创建完成后'a','c'自动按照字典序排序,并且创建时自定加上索引  
  18. 0  5  1  
  19. 1  6  2  
创建完成后'a','c'自动按照字典序排序,并且创建时自定加上索引

如果指定了columns名称,则会按照指定顺序创建。

[python] view plain copy
  1. In [210]: df=DataFrame(data,columns=['c','a'])  
  2.   
  3. In [211]: df  
  4. Out[211]:   
  5.    c  a    #按照指定顺序创建。  
  6. 0  1  5  
  7. 1  2  6  


1.3 传入嵌套字典(字典的值也是字典)创建DataFrame

列名:嵌套字典的外层子键
索引:内层键

[python] view plain copy
  1. In [227]: nest_dict={'shanghai':{2015:100,2016:101},'beijing':{2015:102,2016:103}}  
  2.   
  3. In [228]: nest_dict  
  4. Out[228]: {'beijing': {20151022016103}, 'shanghai': {20151002016101}}  
  5.   
  6. In [229]: df1=DataFrame(nest_dict)  
  7.   
  8. In [230]: df1  
  9. Out[230]:   
  10.       beijing  shanghai  
  11. 2015      102       100  
  12. 2016      103       101  

【pandas】[2] DataFrame 基础,创建DataFrame和增删改查基本操作(1)

2.DataFrame 增删改查

2.1.增

为不存在的列赋值会创建新列
[python] view plain copy
  1. In [219]: df['b']=1  
  2.   
  3. In [220]: df  
  4. Out[220]:   
  5.    c  a  b  
  6. 0  1  5  1  
  7. 1  2  6  1  


2.2.删

用del删除
[python] view plain copy
  1. In [225]: del df['a']  
  2.   
  3. In [226]: df  
  4. Out[226]:   
  5.    c  b  
  6. 0  1  1  
  7. 1  2  1  

用drop() 删除
用drop删除时,删的是视图,并没有真正删除。
[python] view plain copy
  1. <pre name="code" class="python">In [258]: df  
  2. Out[258]:   
  3.    c  b  0  
  4. 0  5  1  6  
  5. 1  5  1  6  
  6. In [259]: df.drop(0,axis=1#删除列Out[259]:     
  7.    c  b  
  8. 0  5  1  
  9. 1  5  1  
  10. In [260]: df  # df的数据并没有改动  
  11. Out[260]:     
  12.    c  b  0  
  13. 0  5  1  6  
  14. 1  5  1  6  

dorp()可以通过axis(行:axis=0 ,列:axis=1)可以控制删除行或列,默认是行。

dorp()也可以同时删除多行或多列

例:

[python] view plain copy
  1. In [271]: df.drop([0,1],axis=1)  
  2. Out[271]:   
  3.    c  b  
  4. 0  6  6  
  5. 1  5  1  

2.3.改

通过赋值进行修改,可以通过定位到行,列,或者具体位置进行赋值修改。

修改具体元素值:
[python] view plain copy
  1. In [242]: df['c'][1]=4  
  2.   
  3. In [243]: df  
  4. Out[243]:   
  5.    c  b  
  6. 0  1  1  
  7. 1  4  1  

修改列:
[python] view plain copy
  1. In [244]: df['c']=5   
  2.   
  3. In [245]: df  
  4. Out[245]:   
  5.    c  b  
  6. 0  5  1  
  7. 1  5  1  

修改行:
[python] view plain copy
  1. df[:1]=6  
  2.   
  3. df  
  4. Out[266]:   
  5.    c  b  
  6. 0  6  6  
  7. 1  5  1  

修改行和列如果传入一组值得话,注意传入数组的长度,如果传入数组长度大于len(df) 则截断,小于df长度则置NaN
[python] view plain copy
  1. In [267]: df[0]=Series([1,2,3])  
  2.   
  3. In [268]: df  
  4. Out[268]:   
  5.    c  b  0  
  6. 0  6  6  1  
  7. 1  5  1  2  
  8.   
  9. In [269]: df[1]=Series([1,])  #增加一列,传入一个值  
  10.   
  11. In [270]: df  
  12. Out[270]:   
  13.    c  b  0   1  
  14. 0  6  6  1   1  
  15. 1  5  1  2 NaN  

2.4.查(索引,选取,过滤)

选取数据 是DataFrame的重点,常用的有 位置切片 和 标签切片置切片遵循Python的切片规则,包括起始位置,但不包括结束位置;但标签切片则同时包括起始标签和结束标签。之所以如此设计是因为在使用标签切片时,通常我们不知道标签的顺序,如果不包含结束标签,很难确定结束标签的前一个标签是什么。

注释: 标准Python / Numpy表达式可以完成这些数据选择工作, 但在生产代码中, 我们推荐使用优化的pandas数据访问方法, .at, .iat, .loc, .iloc 和 .ix.

标签切片和loc选择器:

建议使用这种列标签选取方式,用'.'容易出问题。‘.’的写法容易与其他预留关键字产生冲突

[python] view plain copy
  1. In [276]: data['two']  #建议使用这种列标签选取方式,用'.'容易出问题.。‘.’的写法容易与其他预留关键字产生冲突  
  2.   
  3.   
  4. ‘[ ]’的写法最安全。  
  5. Out[276]:   
  6. a     1  
  7. b     5  
  8. c     9  
  9. d    13  
  10. Name: two, dtype: int32  
  11.   
  12. In [277]: data.two  
  13. Out[277]:   
  14. a     1  
  15. b     5  
  16. c     9  
  17. d    13  
  18. Name: two, dtype: int32  
选择多列:

[python] view plain copy
  1. In [279]: data[['one','two']] #注意多列选择时,传入的事数组, <span style="font-family: Arial, Helvetica, sans-serif;">data[['one','two']] 不能写成 data['one','two']</span>  
  2. Out[279]:  
  3. one two  
  4. 0 1  
  5. 4 5  
  6. 8 9  
  7. 12 13  

使用loc,选取列:

[python] view plain copy
  1. data.loc[:,'one']  
  2. Out[290]:   
  3. a     0  
  4. b     4  
  5. c     8  
  6. d    12  
  7. Name: one, dtype: int32  

使用loc,选取行:

[python] view plain copy
  1. In [293]: data.loc[:'c',:]  
  2. Out[293]:   
  3.    one  two  three  four  
  4. a    0    1      2     3  
  5. b    4    5      6     7  
  6. c    8    9     10    11  

使用loc,选取第一个元素:

[python] view plain copy
  1. In [294]: data.loc[:'a',:'one']  
  2. Out[294]:   
  3.    one  
  4. a    0  

位置切片和ix选择器:

[python] view plain copy
  1. data[0:3]            #等价于data[:3]  
  2. Out[285]:   
  3.    one  two  three  four  
  4. a    0    1      2     3  
  5. b    4    5      6     7  
  6. c    8    9     10    11  

ix用法和loc差不多,loc传入的事行列的名称,ix使用的是相对位置

选取第一行第一列

[python] view plain copy
  1. In [295]: data.ix[:1,:1]  
  2. Out[295]:   
  3.    one  
  4. a    0  


其他pandas数据选择等问题可参考:十分钟搞定pandas