#造表头 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)
注意多个条件(与:&、或:|)
df=df.ix[ (df.name.notnull()) & (df.num<20) , : ]
a=df.iloc[:, [2,3] ] #取第3,4列组成的子表 a=df.ix[:, ["name","time"]] #或者这样
x=map( lambda a: a, df["x"] )
df_group=df.groupby("time") #df_group是一个DataFrameGroupBy对象df_dict=dict(list(df_group)) #转化 for key in df_dict: df2=df_dict[key]
C=pd.merge(A,B, left_on='Aid', right_on='Bid', how='inner')
df['time']=df['time'].astype(int)
df=df.sort_values(by='time')
df.drop( [22,33], axis=0) #22,33是行的index; axis=0表示删除的是行,是横轴#1. 清洗数据。一次性删除 df=df.drop(delete_index_list)
df['timesection']=map( lambda x: 1 if (x/100>=9) else (2 if (x%100>==5) else 3), df['time'])11
一般方法:
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 )
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 )
将一个dataframe对象打乱,并且重新生成索引。打乱行
train_set=train_set.sample(frac=1.0) #打乱train_set=train_set.reset_index(drop=True)
df=df.drop_duplicates()
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") #将数据写入文件
联系客服