张大脸

Python基于pandas的数据处理(一)

1 import pandas as pd, numpy as np
2 dates = pd.date_range('20130101', periods=6)
3 df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD'))
1 mutate + ifelse
1 df['E'] = np.where(df['D'] >= 0, '>=0', '<0')
2 df['F'] = np.random.randint(0, 2, 6)
3 df.assign(G = df.A * df.D) # 或者
4 df['F'] = df['F'].apply(str) #针对单列的
5 df.applymap(str) #这个相当于是mutate_each
2 table

1 pd.value_counts(df["E"])
2 pd.pivot_table(df,index=['E','F'])
3 index 也就是取df的rownames,但与R不一样的在于,df可能有多维rownames
1 df.index
2 df.set_index(['A'], drop = 0, append = 1) # 把已有的列设置为index,可保留之前的index,也可以把新的index在原数据中删除
3 df['dates'] = df.index # 新生成一列dates
4 df.reset_index(level=0, inplace=True) # 同上
5 df.reset_index(level=['index']) # 同上
4 删除列和行
1 df = df.drop('index', axis = 1) # 可以删除多列
2 df.drop(df.index[[1,3]])

5 column names

1 df.columns
2 df.columns = ['a', 'b', 'c', 'e', 'd', 'f'] # 重命名
3 df.rename(columns = {'A':'aa','B':'bb', 'C':'cc', 'D':'dd', 'E':'ee', 'F':'ff'}, inplace=True)
4 df.rename(columns=lambda x: x[1:].upper(), inplace=True) # 也可以用函数 inplace参数的意思就是代替原来的变量,深拷贝

6 哑变量 dummy variables
1 pd.Series(['a|b', np.nan, 'a|c']).str.get_dummies()
7 纯粹的df的矩阵,即不包含column和index
1 df.values
2 df.get_values()
8 summary
1 df.describe() # 只会针对数值型变量做计算
9 rbind
1 df2=pd.DataFrame([[5,6],[7,8]],columns=list('AB'))
2 df.append(df2, ignore_index=True)
10 group by 分组汇总计算,和pivot_table类似
1 df.groupby(['E','F']).mean()
2 df.groupby(['E','F']).agg(['sum', 'mean'])
3 pd.pivot_table(df,index=['E','F'], aggfunc=[np.sum, np.mean])
4 df.pivot_table(index=['E','F'], aggfunc=[np.sum, np.mean]) # 同上
5 df.groupby(['E','F']).agg({'A':['mean','sum'], 'B':'min'}) # groupby 也可以这样写
11 排序
1 df.sort(['A','B'],ascending=[1,0]) # 按列排序,na_position控制NAN的位置
2 df.sort_index(ascending=0) # 按index排序
12 筛选
1 df[(df.A >= -1) & (df.B <= 0)] # 值筛选
2 df[df.E.str.contains(">")] # 包含某个字符,contains筛选的其实是正则表达式
3 df[df.F.isin(['1'])] # 在列表内
13 变量选择
1 df['A'] # 单个的列
2 df[0:3] #
3 df['20130102':'20130104'] # 按index筛选
4 df.loc[:,] # 类似于R里面的dataframe选行和列的方法
5 df.iloc[:,] # iloc只能用数字了

posted on 2016-04-21 19:43  大饼丸  阅读(39412)  评论(0编辑  收藏  举报

导航