美文网首页我爱编程
pandas数据统计

pandas数据统计

作者: Jarlon | 来源:发表于2017-01-03 13:32 被阅读0次

    1.造表DataFrame

    #造表头
    import pandas as pd
    df=pd.DataFrame()
    cols_name=[ "id", "x", "y" ]
    
    #插入一行
    record=[ id, x, y ]
    ser_record=dict( (k,v) for k,v in zip(cols_name, record) )
    df=df.append( pd.Series(ser_record), ignore_index=True)
    
    

    2.表的选择select

    注意多个条件(与:&、或:|)

    df=df.ix[ (df.name.notnull()) & (df.num<20) , : ]
    

    3.取行列

    
    a=df.iloc[:, [2,3] ] #取第3,4列组成的子表
    a=df.ix[:, ["name","time"]] #或者这样
    

    4.取表的单独一个属性列,并且转换为一个list

    x=map( lambda a: a, df["x"] )
    

    5.聚合操作group by

    df_group=df.groupby("time") #df_group是一个DataFrameGroupBy对象
    df_dict=dict(list(df_group)) #转化
    for key in df_dict:
        df2=df_dict[key]
    

    6.两个表连接

    C=pd.merge(A,B, left_on='Aid', right_on='Bid', how='inner')
    

    7.改变一个列的值的类型

    df['time']=df['time'].astype(int)
    

    8.排序,根据某一列排序

    df=df.sort_values(by='time')
    

    9.删除行

    
    df.drop( [22,33], axis=0) #22,33是行的index; axis=0表示删除的是行,是横轴
    
    #1.清洗数据。一次性删除
    df=df.drop(delete_index_list)   
    

    10.根据一列生成另外一列

    df['timesection']=map( lambda x: 1 if (x/100>=9) else (2 if (x%100>==5) else 3), df['time'])11
    

    11.dataframe遍历

    一般方法:

    for iter_index in df.index:
        time=df.loc[iter_index, 'time']
        do_some_thing_with_time(time)
        df.loc[ iter_index, 'time']=time
    

    这个程序是一个网友的程序,他想让do_some_thing_with_time(time)找出DataFrame中time相同的行,给这些time加上后缀,使得DataFrame的每一行time都不同。也就是说需要遍历,然后再修改DataFrame。但是这样会很慢很慢。

    另一个网友有另外一个方法:使用Series.apply函数来调用do_some_thing_with_time(),自然就得到了一个新的处理time列

    df.time2=df.time.apply( do_some_thing_with_time )
    

    12.apply, applymap, map函数

    apply, applymap, map
    apply是作用在dataframe上,用于对row或者column进行计算
    applymap是作用在dataframe上,是元素级别的操作,
    map是作用在Series上,是元素级别的操作

    print frame.apply(lambda x:x.max()-x.min()) #默认是应用在每一列上
    print frame.apply(lambda x:x.max()-x.min(), axis=0) #应用在每一行上
    print frame.applymap( lambda x: '%.2f' % x )
    

    13.打乱dataframe

    将一个dataframe对象打乱,并且重新生成索引。打乱行

    train_set=train_set.sample(frac=1.0)    #打乱
    train_set=train_set.reset_index(drop=True)
    

    14去除重复的

    df=df.drop_duplicates()
    

    15. pandas读写文件

    df=pd.read_csv(filename,encoding="utf-8")  #读取csv文件
    df=pd.read_table(filename,delim_whitespace=True,encoding="utf-8") #读取以空格分隔的一般文本文件
    df.to_csv(outputfile,index=False,encoding="utf-8") #将数据写入文件
    

    相关文章

      网友评论

        本文标题:pandas数据统计

        本文链接:https://www.haomeiwen.com/subject/nzzgvttx.html