pandas数理统计

2017/04/02 python

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. 增加一行

#插入一行
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)

3. 删除行

df.drop( [22,33], axis=0) #22,33是行的index; axis=0表示删除的是行,是横轴

#可以记录下索引,然后一次性删除
df=df.drop(delete_index_list)	

4. 表的选择select

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

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

5. 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 )

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

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

7. 取子表

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

如果加上上面的取某些行的条件,就是取子表了。

8. 取表的单独一个属性列

这个方法是使用map函数,得到的x是一个list

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

9. 聚合操作group by

df_group是一个DataFrameGroupBy对象

df_group=df.groupby("time") 
df_dict=dict(list(df_group)) #转化
for key in df_dict:
    df2=df_dict[key]

10. 两个表连接

joined_df=pd.merge(df1, df2, left_on='id1', right_on='id2', how='inner')

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

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

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

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

13. 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 )

14. 打乱dataframe

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

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

15. 去除重复的行

df=df.drop_duplicates()

16. 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") #将数据写入文件

如果文件太大,需要分块读取。

reader = pd.read_table('tmp.sv', sep='|', chunksize=4)









Search

    Post Directory