pandas 入门

  1. Series
    1. 创建
      1. obj = Series([4, 7, -5, 3])
      2. obj2 = Series([4, 7, -5, 3], index=['d', 'b', 'a', 'c'])

    2. 取索引
      1. ind = obj.index (ind 类型是 ‘pandas.core.index.Int64Index’ )
      2. vvv = ind[0] (vvv 类型是 ‘numpy.int64’ , 可以通过 int() 转换)
    3. 取值(list)
      1. val = obj.values (val 类型是 ‘numpy.ndarray’ )
      2. al = val.tolist() (转为Python的list,其中每个值的类型是 long )
    4. 取单个值
      1. obj[‘单个索引名称’]
    5. 其它操作:
      1. 过滤:
        1. obj2[obj2 > 0]

      2. 加减乘除:
        1. obj2 * 2

      3. 判断是否包含:
        1. 'b' in obj2                  (如果索引中存在 b,返回 True)

  2. Dataframe
    1. 创建
      1. data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'],
        'year': [2000, 2001, 2002, 2001, 2002],
        'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}
        frame = DataFrame(data)
      2. dict1 = { \
        'timestamp' : str(timestamp), \
        'guifei' : float(itemList[16]) \
        }
        buyDataList.append(dict1)
        ### use 'list of dict' to construct dataframe
        buyDf = pd.DataFrame(buyDataList, columns=['timestamp' 'qita'])
      3. a
        ## create df with list of tuple

        data1 = []
        for item in resList:
        l1 = item.split(',')
        l1.insert(0,str('sz002466'))
        tu1 = tuple(l1)
        data1.append(tu1)

        df = pd.DataFrame(data1, columns=eastTableColumns)
      4. a
        ## create df with list of list
        df4 = pd.DataFrame([list6], columns=eastTableColumns)
      5. a
        ### existing df append list as Series
        tt7 = pd.Series(list1, index=list)
        tt7.name = ('sz002407', '2016-08-02')
        df3 = df3.append(tt7)


      6.       #### create df by list of list and combine df
        arrays = [np.array(['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']),
        np.array(['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two'])]
        df = pd.DataFrame(np.random.randn(8, 4), index=arrays)

        narr = [np.array(['bar', 'baz', 'foo', 'qux']),
        np.array(['three', 'three', 'three', 'three'])]

        l1 = [1,3,5,7]
        l2 = [2,3,4,5]
        l3 = [5,7,5,6]
        l4 = [24,4,6,7]
        alll = [l1,l2,l3,l4]
        df1 = pd.DataFrame( alll , index=narr)

        frames = [ df , df1 ]
        res = pd.concat(frames)
      7. 
        
    2. 取索引
      1. ind = obj.index (ind 类型是 ‘pandas.core.index.Int64Index’ )
      2. vvv = ind[0] (vvv 类型是 ‘numpy.int64’ , 可以通过 int() 转换)
    3. 设置index
      1. df1 = df.set_index([‘code’, ‘date’])
    4. 取单列(list)
      1. t2 = df1[‘code’] (t2 类型是 Series )
      2. t3 = df1.code  
      3. t4 = df1[[‘code’, ‘name’]] ### 取多个列
    5. 取部分行
      1. df[0:3]
      2. data[data[‘three’] > 5]
    6. 几种通过索引选取行列的方法:
      1. .loc
        1. 基于行索引label选择部分行列
        2. 例子:
          1. dfl.loc['20130102':'20130104']     #### 选取 部分行 

          2. df.loc[:,['A', 'B'] ]    #### 选取 A列和 B列的所有行
          3. df.loc['20130102':'20130104'   ,['A', 'B'] ]    ### 行列都指定
      2. .iloc (slice的话是含前不含后)
        1. 基于行索引数值选择部分行列
        2. 例子:
          1. s1.iloc[:3]       ### 取前3行
          2. s1.iloc[3]        ### 取第 4 行
          3. df1.iloc[1:5, 2:4]     #### 1:5  是行序号, 2:4是列序号
          4. 
            
      3. .ix
        1. 基于行索引label或者数值选择部分行列
        2. 例子:
          1. df.ix[[('bar', 'two'), ('qux', 'on ')]]    ### 圆括号里面的是组合行索引,索引包含2个值
      4. .布尔型索引
        1. 基于条件判断选择部分行
        2. 例子:
          1. dfl[df.A > 0 ]
          2. df[ df > 0 ]
          3. df.code.isin([‘002407’])
          4. df.loc[df.code.isin([‘002407’])]
          5. de  >df[(df.one >=1 ) & (df.one 

          6. de  >df1.loc[ df1.Per == '-' , 'Per' ] = 0de>
          7. dfwithnostop = dfndaylow[ ~dfndaylow[1].isin( dfstop1.drop_duplicates().tolist()  )  ]             


          8. ####pandas 取反符号是 ~


          9.   
      5. .loc
        1. 基于行索引选择部分行
        2. 例子:
          1. dfl
    7. 访问多重index
      1. 例子:
        1. arrays = [np.array([‘bar’, ‘bar’, ‘baz’, ‘baz’, ‘foo’, ‘foo’, ‘qux’, ‘qux’]),
        2.           np.array([‘one’, ‘two’, ‘one’, ‘two’, ‘one’, ‘two’, ‘one’, ‘two’])] 
        3. df = pd.DataFrame(np.random.randn(8, 4), index=arrays)
        4. df.ix[(‘aux’,’one’),0] = 3.5
        5. df.ix[(‘aux’,’one’),(0, 1, 2, 3) ] = [3.5, 3.6, 3.7, 3.8]


    8. 取单个值
      1. obj[‘单个索引名称’]
      2. dfOne = selDf[start:end]

        # get first value
        code = dfOne['code'].get(0)
        tstamp = dfOne['timestamp'].get(0)
        price = float( dfOne['price'].get(0) )
        amount = abs( int( dfOne['amount'].get(0) ) )

    9. 其它操作:
      1. 修改列:
        1. frame2['debt'] = 16.5         (如果原来没有'debt' 列,这个操作就增加了一列,默认值是16.5 )

        2. frame2['eastern'] = frame2.state == 'Ohio'        
        3. (创建新的列,每个的值为一个判断语句的返回值(frame2.state == 'Ohio'))  
        4. del frame2['eastern']        (删除列

      2. 修改单个值
        1. 推荐使用 df.loc[row_index,col_indexer] 方式。
        2. 这样可以减少/避免由于内存layout(不可预测)因素导致的view/copy 问题。
      3. 转置(行列标题交换):
        1. vv = frame.T   (转置完的类型还是 Dataframe )

      4. 选择头尾部分:
        1. df.head(3)                  (如果索引中存在 b,返回 True)

        2. df.tail(3)
      5. 基本统计使用describe()函数
        1. df2 = df.describe()   (类型还是 Dataframe )([u'count', u'mean', u'std', u'min', u'25%', u'50%', u'75%', u'max']
      6. 选择头尾部分:
        1. df.head(3)                  (如果索引中存在 b,返回 True)

        2. df.tail(3)
      7. sort 函数:
        1. 可以按多个列先后排序,每个列可以指定是升序还是降序
          1. 例子: df.sort([‘c1’,‘c2’], ascending=[False,True])
          2. dfNew = dfTable.sort_index(ascending=False) ### 按照 index 排序
      8. groupby 函数:
        1. sf
      9. 求排序值
        1. frame[‘sum_order’] = frame[‘sum’].rank()
        2. frame[‘sum_sq_order’] = frame[‘sum_sq’].rank()
        3. frame[‘max_order’] = frame[‘max’].rank()
        4. frame[‘mean_order’] = frame[[‘sum_order’, ‘sum_sq_order’, ‘max_order’]].mean(axis=1)

  • 常见操作:
    1. data < 5 ## 过滤
    2. data[ data < 5 ] = 0 ## 替换
    3. df[24] = df[24].str[:10] ## 仅保留前10个字符


    kbdf = buy_df.copy()



    sdf = sdf.sort(['date','time'])

    sortedBdf = matchBuyDf.sort(['amount','price'], ascending=[False,True])

    df2 = df.sort_values(by=[timestamp], ascending=[False] )



    # 寻找满足条件的行的index(集合),然后使用 loc 函数匹配

    t1 = bdf[ (bdf['date'] > lastSellDate) | ( (bdf['date'] == lastSellDate) & (bdf['time'] > lastSellTime) ) ].index

    df.loc[t1, 'status'] = 2

    # 如果是DF 中的单独一行,需要使用 “name”属性。

    df.loc[sortedBdf.iloc[0].name,'status'] = 1

    df = df[ (df['flag'] == sell_flag) | (df['flag'] == buy_flag) ]



    # 选取 DF 中的某几列

    df = df[list(df.columns[:7]) + list(df.columns[10:])]

    df2[ [4 , 10, 14, 18, 22, 23 ] ]



    # 遍历某个 DF,其中 sdf_row 是当前行的 series

    for sell_df_index, sdf_row in sdf.iterrows():

    sdf_row['price'] # series 方式



    # 使用该函数读取文件

    # mycols 是一个自定义的列表,其中包括 code, amount

    # 通过 dtype 参数指定数据类型

    df = pd.read_csv(pandasInputFile, sep=',', skiprows=5, index_col=False,

    names=mycols, dtype={'code':np.object, 'amount':np.int16} )

    ## 如上,mycols可以是一个list,在dtype参数里面可以指定mycols中包含的列的数据类型

    df2.to_csv('reffiles/stBasic.txt', sep='|', encoding='utf-8')





    # df 中字符串的操作

    df.loc[ df[1].str.startswith('6') , 1] = 'sh' + df[1].astype(str)

    df2[[4,10]] = df2[[4,10]].applymap(lambda x : x.strip('%') ).apply( pd.to_numeric ) ### 去除字符串末尾的百分号,并且转换成数值类型






































    find命令的使用(查找文件或者文件内容)

    1. 通过文件名查找法
      1. find / -name httpd.conf
        1. 直接在find后面写上 -name,表明要求系统按照文件名查找,最后写上httpd.conf这个目标文件名即可。稍等一会系统会在计算机屏幕上显示出查找结果列表:  /etc/httpd/conf/httpd.conf
      2. find /etc -name ‘*srm*’
        1. 如果只知道部分文件名,可以使用这种通配符方式查找。
    2. 根据文件属性查找法
      1. 根据文件大小
        1. find / -size 1500c
          1. 字符 c 表明这个要查找的文件的大小是以bytes为单位,这是查找等于1500byte的文件
        2. find/ -size +10000000c
          1. 这个命令,则标明我们指定系统在根目录中查找出大于10000000字节的文件并显示出来,”+”表示大于,”-“表示小于,这两个符号还可以用于其它文件属性查找中,下面会看到例子。
      2. 其它文件属性
        1. find / -amin -10 # 查找在系统中最后10分钟访问的文件
          find / -atime -2 # 查找在系统中最后48小时访问的文件
          find / -empty # 查找在系统中为空的文件或者文件夹
          find / -group cat # 查找在系统中属于 groupcat的文件
          find / -mmin -5 # 查找在系统中最后5分钟里修改过的文件
          find / -mtime -1 #查找在系统中最后24小时里修改过的文件
          find / -nouser #查找在系统中属于作废用户的文件
          find / -user fred #查找在系统中属于FRED这个用户的文件
        2. 说明
          1.        -amin n
              查找系统中最后N分钟访问的文件
              -atime n
              查找系统中最后n*24小时访问的文件
              -cmin n
              查找系统中最后N分钟被改变状态的文件
              -ctime n
              查找系统中最后n*24小时被改变状态的文件
              -empty
              查找系统中空白的文件,或空白的文件目录,或目录中没有子目录的文件夹
              -false
              查找系统中总是错误的文件
              -fstype type
              查找系统中存在于指定文件系统的文件,例如:ext2 .
              -gid n
              查找系统中文件数字组 ID 为 n的文件
              -group gname
              查找系统中文件属于gnam文件组,并且指定组和ID的文件
          2. -type 查找某一类型的文件
            1. b – 块设备文件。
              d – 目录。
              c – 字符设备文件。
              p – 管道文件。
              l – 符号链接文件。
              f – 普通文件。
            2. 例子
              1. find logs -type f -mtime +5 -exec rm {} \;
    3. find命令的控制选项
      1.   -daystart
          .测试系统从今天开始24小时以内的文件,用法类似-amin
          -depth
          使用深度级别的查找过程方式,在某层指定目录中优先查找文件内容
          -follow
          遵循通配符链接方式查找; 另外,也可忽略通配符链接方式查询。  (说明:使用-follow选项后,find命令则遵循通配符链接方式进行查找,除非你指定这个选项,否则一般情况下find命令将忽略通配符链接方式进行文件查找。)
          -help
          显示命令摘要
          -maxdepth levels
          在某个层次的目录中按照递减方法查找。(例子:find . -maxdepth 2 -name fred)
          -mount
          不在文件系统目录中查找, 用法类似 -xdev.
          -noleaf
          禁止在非UNUX文件系统,MS-DOS系统,CD-ROM文件系统中进行最优化查找
          -version
          打印版本数字
    4. 混合查找方式
      1. find /tmp -size +10000000c -and -mtime +2
      2. find / -user fred -or -user george
    5. 使用exec或ok来执行shell命令
      1. exec选项后面跟随着所要执行的命令或脚本,然后是一对儿 {},一个空格和一个\,最后是一个分号。     cmd {} \;
    二、find命令的例子;


    1、查找当前用户主目录下的所有文件:

    下面两种方法都可以使用

    $ find $HOME -print
    $ find ~ -print

    2、让当前目录中文件属主具有读、写权限,并且文件所属组的用户和其他用户具有读权限的文件;
    $ find . -type f -perm 644 -exec ls -l {} \;



    3、为了查找系统中所有文件长度为0的普通文件,并列出它们的完整路径;

    $ find / -type f -size 0 -exec ls -l {} \;



    4、查找/var/logs目录中更改时间在7日以前的普通文件,并在删除之前询问它们;

    $ find /var/logs -type f -mtime +7 -ok rm {} \;



    5、为了查找系统中所有属于root组的文件;

    $find . -group root -exec ls -l {} \;
    -rw-r--r--    1 root     root          595 10月 31 01:09 ./fie1



    6、find命令将删除当目录中访问时间在7日以来、含有数字后缀的admin.log文件。

    该命令只检查三位数字,所以相应文件的后缀不要超过999。先建几个admin.log*的文件 ,才能使用下面这个命令

    $ find . -name "admin.log[0-9][0-9][0-9]" -atime -7  -ok
    rm {} \;
    ? n
    ? n
    ? n
    ? n



    7、为了查找当前文件系统中的所有目录并排序;

    $ find . -type d | sort



    8、为了查找系统中所有的rmt磁带设备;

    $ find /dev/rmt -print



    三、xargs

    xargs – build and execute command lines from standard input
    在使用find命令的-exec选项处理匹配到的文件时, find命令将所有匹配到的文件一起传递给exec执行。但有些系统对能够传递给exec的命令长度有限制,这样在find命令运行几分钟之后,就会出现溢出错误。错误信息通常是“参数列太长”或“参数列溢出”。这就是xargs命令的用处所在,特别是与find命令一起使用。
    find命令把匹配到的文件传递给xargs命令,而xargs命令每次只获取一部分文件而不是全部,不像-exec选项那样。这样它可以先处理最先获取的一部分文件,然后是下一批,并如此继续下去。
    在有些系统中,使用-exec选项会为处理每一个匹配到的文件而发起一个相应的进程,并非将匹配到的文件全部作为参数一次执行;这样在有些情况下就会出现进程过多,系统性能下降的问题,因而效率不高;
    而使用xargs命令则只有一个进程。另外,在使用xargs命令时,究竟是一次获取所有的参数,还是分批取得参数,以及每一次获取参数的数目都会根据该命令的选项及系统内核中相应的可调参数来确定。
    来看看xargs命令是如何同find命令一起使用的,并给出一些例子。
    下面的例子查找系统中的每一个普通文件,然后使用xargs命令来测试它们分别属于哪类文件

    #find . -type f -print | xargs file
    ./.kde/Autostart/Autorun.desktop: UTF-8 Unicode English text
    ./.kde/Autostart/.directory:      ISO-8859 text\
    ......


    在整个系统中查找内存信息转储文件(core dump) ,然后把结果保存到/tmp/core.log 文件中:

    $ find / -name "core" -print | xargs echo "" >/tmp/core.log


    上面这个执行太慢,我改成在当前目录下查找

    #find . -name "file*" -print | xargs echo "" > /temp/core.log
    # cat /temp/core.log
    ./file6


    在当前目录下查找所有用户具有读、写和执行权限的文件,并收回相应的写权限:

    # ls -l
    drwxrwxrwx    2 sam      adm          4096 10月 30 20:14 file6
    -rwxrwxrwx    2 sam      adm             0 10月 31 01:01 http3.conf
    -rwxrwxrwx    2 sam      adm             0 10月 31 01:01 httpd.conf

    # find . -perm -7 -print | xargs chmod o-w
    # ls -l
    drwxrwxr-x    2 sam      adm          4096 10月 30 20:14 file6
    -rwxrwxr-x    2 sam      adm             0 10月 31 01:01 http3.conf
    -rwxrwxr-x    2 sam      adm             0 10月 31 01:01 httpd.conf


    用grep命令在所有的普通文件中搜索hostname这个词:

    # find . -type f -print | xargs grep "hostname"
    ./httpd1.conf:#     different IP addresses or hostnames and have them handled by the
    ./httpd1.conf:# VirtualHost: If you want to maintain multiple domains/hostnames
    on your


    用grep命令在当前目录下的所有普通文件中搜索hostnames这个词:

    # find . -name \* -type f -print | xargs grep "hostnames"
    ./httpd1.conf:#     different IP addresses or hostnames and have them handled by the
    ./httpd1.conf:# VirtualHost: If you want to maintain multiple domains/hostnames
    on your


    注意,在上面的例子中, \用来取消find命令中的*在shell中的特殊含义。
    find命令配合使用exec和xargs可以使用户对所匹配到的文件执行几乎所有的命令。

    四、find 命令的参数

    下面是find一些常用参数的例子,有用到的时候查查就行了,像上面前几个贴子,都用到了其中的的一些参数,也可以用man或查看论坛里其它贴子有find的命令手册

    1、使用name选项

    文件名选项是find命令最常用的选项,要么单独使用该选项,要么和其他选项一起使用。
    可以使用某种文件名模式来匹配文件,记住要用引号将文件名模式引起来。
    不管当前路径是什么,如果想要在自己的根目录$HOME中查找文件名符合*.txt的文件,使用~作为 ‘pathname’参数,波浪号~代表了你的$HOME目录。

    $ find ~ -name "*.txt" -print


    想要在当前目录及子目录中查找所有的‘ *.txt’文件,可以用:

    $ find . -name "*.txt" -print


    想要的当前目录及子目录中查找文件名以一个大写字母开头的文件,可以用:

    $ find . -name "[A-Z]*" -print


    想要在/etc目录中查找文件名以host开头的文件,可以用:

    $ find /etc -name "host*" -print


    想要查找$HOME目录中的文件,可以用:

    $ find ~ -name "*" -print 或find . -print


    要想让系统高负荷运行,就从根目录开始查找所有的文件。

    $ find / -name "*" -print


    如果想在当前目录查找文件名以两个小写字母开头,跟着是两个数字,最后是.txt的文件,下面的命令就能够返回名为ax37.txt的文件:

    $find . -name "[a-z][a-z][0--9][0--9].txt" -print



    2、用perm选项

    按照文件权限模式用-perm选项,按文件权限模式来查找文件的话。最好使用八进制的权限表示法。
    如在当前目录下查找文件权限位为755的文件,即文件属主可以读、写、执行,其他用户可以读、执行的文件,可以用:

    $ find . -perm 755 -print


    还有一种表达方法:在八进制数字前面要加一个横杠-,表示都匹配,如-007就相当于777,-006相当于666

    # ls -l
    -rwxrwxr-x    2 sam      adm             0 10月 31 01:01 http3.conf
    -rw-rw-rw-    1 sam      adm         34890 10月 31 00:57 httpd1.conf
    -rwxrwxr-x    2 sam      adm             0 10月 31 01:01 httpd.conf
    drw-rw-rw-    2 gem      group        4096 10月 26 19:48 sam
    -rw-rw-rw-    1 root     root         2792 10月 31 20:19 temp

    # find . -perm 006
    # find . -perm -006
    ./sam
    ./httpd1.conf
    ./temp


    -perm mode:文件许可正好符合mode
    -perm +mode:文件许可部分符合mode
    -perm -mode: 文件许可完全符合mode

    3、忽略某个目录

    如果在查找文件时希望忽略某个目录,因为你知道那个目录中没有你所要查找的文件,那么可以使用-prune选项来指出需要忽略的目录。在使用-prune选项时要当心,因为如果你同时使用了-depth选项,那么-prune选项就会被find命令忽略。
    如果希望在/apps目录下查找文件,但不希望在/apps/bin目录下查找,可以用:

    $ find /apps -path "/apps/bin" -prune -o -print



    4、使用find查找文件的时候怎么避开某个文件目录

    比如要在/usr/sam目录下查找不在dir1子目录之内的所有文件

    find /usr/sam -path "/usr/sam/dir1" -prune -o -print


    find [-path ..] [expression] 在路径列表的后面的是表达式


    -path “/usr/sam” -prune -o -print 是 -path “/usr/sam” -a -prune -o
    -print 的简写表达式按顺序求值, -a 和 -o 都是短路求值,与 shell 的 && 和 || 类似如果 -path “/usr/sam” 为真,则求值 -prune , -prune 返回真,与逻辑表达式为真;否则不求值 -prune,与逻辑表达式为假。如果 -path “/usr/sam” -a -prune 为假,则求值 -print ,-print返回真,或逻辑表达式为真;否则不求值 -print,或逻辑表达式为真。
    这个表达式组合特例可以用伪码写为

    if -path "/usr/sam"  then
              -prune
    else
              -print


    避开多个文件夹

    find /usr/sam \( -path /usr/sam/dir1 -o -path /usr/sam/file1 \) -prune -o -print


    圆括号表示表达式的结合。

    \ 表示引用,即指示 shell 不对后面的字符作特殊解释,而留给 find 命令去解释其意义。


    查找某一确定文件,-name等选项加在-o 之后

    #find /usr/sam  \(-path /usr/sam/dir1 -o -path /usr/sam/file1 \) -prune -o -name "temp" -print



    5、使用user和nouser选项

    按文件属主查找文件,如在$HOME目录中查找文件属主为sam的文件,可以用:

    $ find ~ -user sam -print


    在/etc目录下查找文件属主为uucp的文件:

    $ find /etc -user uucp -print


    为了查找属主帐户已经被删除的文件,可以使用-nouser选项。这样就能够找到那些属主在/etc/passwd文件中没有有效帐户的文件。在使用-nouser选项时,不必给出用户名; find命令能够为你完成相应的工作。
    例如,希望在/home目录下查找所有的这类文件,可以用:

    $ find /home -nouser -print



    6、使用group和nogroup选项

    就像user和nouser选项一样,针对文件所属于的用户组, find命令也具有同样的选项,为了在/apps目录下查找属于gem用户组的文件,可以用:

    $ find /apps -group gem -print


    要查找没有有效所属用户组的所有文件,可以使用nogroup选项。下面的find命令从文件系统的根目录处查找这样的文件

    $ find / -nogroup-print



    7、按照更改时间或访问时间等查找文件

    如果希望按照更改时间来查找文件,可以使用mtime,atime或ctime选项。如果系统突然没有可用空间了,很有可能某一个文件的长度在此期间增长迅速,这时就可以用mtime选项来查找这样的文件。
    用减号-来限定更改时间在距今n日以内的文件,而用加号+来限定更改时间在距今n日以前的文件。
    希望在系统根目录下查找更改时间在5日以内的文件,可以用:

    $ find / -mtime -5 -print


    为了在/var/adm目录下查找更改时间在3日以前的文件,可以用:

    $ find /var/adm -mtime +3 -print



    8、查找比某个文件新或旧的文件

    如果希望查找更改时间比某个文件新但比另一个文件旧的所有文件,可以使用-newer选项。它的一般形式为:

    newest_file_name ! oldest_file_name


    其中,!是逻辑非符号。
    查找更改时间比文件sam新但比文件temp旧的文件:
    例:有两个文件

    -rw-r--r--    1 sam      adm             0 10月 31 01:07 fiel
    -rw-rw-rw-    1 sam      adm         34890 10月 31 00:57 httpd1.conf
    -rwxrwxr-x    2 sam      adm             0 10月 31 01:01 httpd.conf
    drw-rw-rw-    2 gem      group        4096 10月 26 19:48 sam
    -rw-rw-rw-    1 root     root         2792 10月 31 20:19 temp

    # find -newer httpd1.conf  ! -newer temp -ls
    1077669    0 -rwxrwxr-x   2 sam      adm             0 10月 31 01:01 ./httpd.conf
    1077671    4 -rw-rw-rw-   1 root     root         2792 10月 31 20:19 ./temp
    1077673    0 -rw-r--r--   1 sam      adm             0 10月 31 01:07 ./fiel


    查找更改时间在比temp文件新的文件:

    $ find . -newer temp -print

    9、使用type选项

    在/etc目录下查找所有的目录,可以用:

    $ find /etc -type d -print


    在当前目录下查找除目录以外的所有类型的文件,可以用:

    $ find . ! -type d -print


    在/etc目录下查找所有的符号链接文件,可以用

    $ find /etc -type l -print



    10、使用size选项

    可以按照文件长度来查找文件,这里所指的文件长度既可以用块(默认单位block,512 bytes)来计量,也可以用字节来计量。以字节计量文件长度的表达形式为N c;以块计量文件长度只用数字表示即可。
    在按照文件长度查找文件时,一般使用这种以字节表示的文件长度,在查看文件系统的大小,因为这时使用块来计量更容易转换。
    在当前目录下查找文件长度大于1 M字节的文件:

    $ find . -size +1000000c -print


    在/home/apache目录下查找文件长度恰好为100字节的文件:

    $ find /home/apache -size 100c -print


    在当前目录下查找长度超过10块的文件(一块等于512字节):

    $ find . -size +10 -print
    $ find . -size +200 -type f >  ~/bigfile.txt
    查找大于100K,是普通文件(非目录)的文件列表,并保存结果到文件“~/bigfile.txt”中。



    11、使用depth选项

    在使用find命令时,可能希望先匹配所有的文件,再在子目录中查找。使用depth选项就可以使find命令这样做。这样做的一个原因就是,当在使用find命令向磁带上备份文件系统时,希望首先备份所有的文件,其次再备份子目录中的文件。
    在下面的例子中, find命令从文件系统的根目录开始,查找一个名为CON.FILE的文件。
    它将首先匹配所有的文件然后再进入子目录中查找。

    $ find / -name "CON.FILE" -depth -print



    12、使用mount选项

    在当前的文件系统中查找文件(不进入其他文件系统),可以使用find命令的mount选项。
    从当前目录开始查找位于本文件系统中文件名以XC结尾的文件:

    $ find . -name "*.XC" -mount -print

    13、对选项“取非”
    例子:
    find /dev ! \( -type d -o -type c -o -type -b \)
    上例中的感叹号(!)表示查找不符合指定条件(文件类型是 -b or -c or -d )的文件,比如 -f 的文件就会被打印出来

    find . \( -name “*.h” -o -name “*.cpp” -o -name “*.cxx” -o -name “*.c” \) -follow > ~/tempfile4
    tar cvf ~/6850code.tar -I ~/tempfile4

    例子: 打印当前目录下所有文件,但skip 目录(perlscript )和目录(shellscript )下的文件
    find .  -name perlscript -prune -o -name shellscript -prune -o -print
    find . -name “calcEepromCrc.c” -o -name perlscript -prune

    pandas Merge, join, and concatenate

    合并,联合以及连接

    Merge, join, and concatenate

    http://pandas.pydata.org/pandas-docs/stable/merging.html

    pd.concat(objs, axis=0, join=’outer’, join_axes=None, ignore_index=False,
              keys=None, levels=None, names=None, verify_integrity=False,
              copy=True)
    • objs : a sequence or mapping of Series, DataFrame, or Panel objects. If a dict is passed, the sorted keys will be used as the keys argument, unless it is passed, in which case the values will be selected (see below). Any None objects will be dropped silently unless they are all None in which case a ValueError will be raised.
    • axis : {0, 1, …}, default 0. The axis to concatenate along.
    • join : {‘inner’, ‘outer’}, default ‘outer’. How to handle indexes on other axis(es). Outer for union and inner for intersection.
    • ignore_index : boolean, default False. If True, do not use the index values on the concatenation axis. The resulting axis will be labeled 0, …, n – 1. This is useful if you are concatenating objects where the concatenation axis does not have meaningful indexing information. Note the index values on the other axes are still respected in the join.
    • join_axes : list of Index objects. Specific indexes to use for the other n – 1 axes instead of performing inner/outer set logic.
    • keys : sequence, default None. Construct hierarchical index using the passed keys as the outermost level. If multiple levels passed, should contain tuples.
    • levels : list of sequences, default None. Specific levels (unique values) to use for constructing a MultiIndex. Otherwise they will be inferred from the keys.
    • names : list, default None. Names for the levels in the resulting hierarchical index.
    • verify_integrity : boolean, default False. Check whether the new concatenated axis contains duplicates. This can be very expensive relative to the actual data concatenation.
    • copy : boolean, default True. If False, do not copy data unnecessarily.

    frames  = [ df1, df2, df3 ]

    ·         concat 的合并方向选项:
    o   1. axis = 0 (默认选项) 行跟着行
    o   2. axis = 1                      列跟着列

    ·         concat 的合并交集方式:
    o   1. join=’outer’ (默认选项) 取并集,以求不损失数据(信息)
    o   2. join=’inner’                      取交集,即所有df 中都存在的index
    o   3. join_axes=[df1.index]         以某个dfindex范围进行判断,在里面的就合并,不在里面的就舍弃。

    Append


    Merge根据列的值,而非index,来进行合并

    pd.merge(left, right, how=’inner’, on=None, left_on=None, right_on=None,
             left_index=False, right_index=False, sort=True,
             suffixes=(‘_x’, ‘_y’), copy=True, indicator=False)
    • left: A DataFrame object
    • right: Another DataFrame object
    • on: Columns (names) to join on. Must be found in both the left and right DataFrame objects. If not passed and left_index and right_index are False, the intersection of the columns in the DataFrames will be inferred to be the join keys
    • left_on: Columns from the left DataFrame to use as keys. Can either be column names or arrays with length equal to the length of the DataFrame
    • right_on: Columns from the right DataFrame to use as keys. Can either be column names or arrays with length equal to the length of the DataFrame
    • left_index: If True, use the index (row labels) from the left DataFrame as its join key(s). In the case of a DataFrame with a MultiIndex (hierarchical), the number of levels must match the number of join keys from the right DataFrame
    • right_index: Same usage as left_index for the right DataFrame
    • how: One of ‘left’, ‘right’, ‘outer’, ‘inner’. Defaults to inner. See below for more detailed description of each method
    • sort: Sort the result DataFrame by the join keys in lexicographical order. Defaults to True, setting to False will improve performance substantially in many cases
    • suffixes: A tuple of string suffixes to apply to overlapping columns. Defaults to (‘_x’, ‘_y’).
    • copy: Always copy data (default True) from the passed DataFrame objects, even when reindexing is not necessary. Cannot be avoided in many cases but may improve performance / memory usage. The cases where copying can be avoided are somewhat pathological but this option is provided nonetheless.
    • indicator: Add a column to the output DataFrame called _merge with information on the source of each row. _merge is Categorical-type and takes on a value of left_only for observations whose merge key only appears in ‘left’ DataFrame, right_only for observations whose merge key only appears in ‘right’ DataFrame, and both if the observation’s merge key is found in both.

    ·         如何使用 how 参数例子:

    ·         如何使用 indicator参数例子:
    ·        In [50]: pd.merge(df1, df2, on=’col1′, how=’outer’, indicator=True)
    ·        Out[50]:
    ·           col1 col_left  col_right      _merge
    ·        0     0        a        NaN   left_only
    ·        1     1        b        2.0        both
    ·        2     2      NaN        2.0  right_only
    ·        3     2      NaN        2.0  right_only

    Join从两个可能index不相同的df中,把部分列合并到一起

    1
    2

    3

    ]]

    PreProcessor

    6.1    File Include Directive


    ���ָ�ʽ��

           #include                                    ��ʽһ

           #include ��filename��                             ��ʽ��

     

     

     

    ��ʽһ ��ʾ������ϵͳ��standard Ŀ¼���ҵ����ļ���

     

    ��ʽ�� ��ʾ������ϵͳ�� alternative Ŀ¼���ҵ����ļ���

    l         ����ʹ�þ���·����ָ���ļ�λ��

    l         ����ļ���ǰû��·�������Ȳ����û��ĵ�ǰĿ¼�����û�ҵ����ٲ��� standard Ŀ¼��

     

    �����included ���ļ���Ҳ�� file include directive�� ����ЩҲ�ᱻ��ִ�С�

     

     

    6.2    Conditional Compilation


    #ifdef   

    #ifndef           

    #endif             

     

     

    #ifdef �� #ifndef ��������Ϊ��ʼ��־���� #endif ���ǽ�����־��

    ������������������������Ƿ�compile��

     

    ��Щ������Ƕ��ʹ�á�

     

    �����䣺

     

    #define