作者:lianghc

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

1.DataFrame创建:


1.标准格式创建


2.等长列表组成的字典来创建


3.嵌套字典(字典的值也是字典)创建


1.1  标准格式创建

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


    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 用传入等长列表组成的字典来创建

      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'自动按照字典序排序,并且创建时自定加上索引  
      18. 0  5  1  
      19. 1  6  2


      创建完成后'a','c'自动按照字典序排序,并且创建时自定加上索引


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



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

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


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


      索引:内层键



        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': {2015: 102, 2016: 103}, 'shanghai': {2015: 100, 2016: 101}}  
        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




        dataframe python 根据已有结构生成 python建立dataframe_python

        2.DataFrame 增删改查

        2.1.增


        为不存在的列赋值会创建新列


          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删除



          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删除时,删的是视图,并没有真正删除。


          1. <pre name="code" class="python">In [258]: df  
          2. Out[258]:   
          3. 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. 0  
          13. 0  5  1  6  
          14. 1  5  1  6


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

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

          例:


          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.改


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



          修改具体元素值:


            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




              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


              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

              1. In [267]: df[0]=Series([1,2,3])  
              2.   
              3. In [268]: df  
              4. Out[268]:   
              5. 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. 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选择器:






              ‘.’的写法容易与其他预留关键字产生冲突



              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





              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. a 0 1  
              5. b 4 5  
              6. c 8 9  
              7. d 12 13


              使用loc,选取列:




              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,选取行:




              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,选取第一个元素:



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



              位置切片和ix选择器:





              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使用的是相对位置

              选取第一行第一列




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


              其他pandas数据选择等问题可参考:

              十分钟搞定pandas