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.取表的单独一个属性列,并且转换为一个listx=map( lambda a: a, df["x"] ) 5.聚合操作group bydf_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 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") #将数据写入文件 |
|