张大脸

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


14 抽样
1 df.sample(10, replace = True)
2 df.sample(3)
3 df.sample(frac = 0.5) # 按比例抽样
4 df.sample(frac = 10, replace = True,weights = np.random.randint(1,10,6)) # 对样本加权
5 df.sample(3, axis = 1) # 变量抽样
15 join(即 merge)

1 pd.merge(df.sample(4), df.sample(4), how = "left", on = "A", indicator = True)
16 随机数

numpy.random.rand(3, 2) # 按维度生成[0,1)之间的均匀分布随机数
np.random.randn(2,5) # 按维度生成标准正太分布随机数
np.random.randint(2, size=10) # randint(low[, high, size])生成随机整数,默认low为0,high必填,size默认为1
np.random.bytes(10) # 返回随机字节
a=np.arange(10)
np.random.shuffle(a) # 洗牌
a=np.arange(9).reshape(3, 3)
np.random.shuffle(a) # 若是数组,则只会打乱第一维
np.random.permutation(10) # 随机排列,对于多维序列也适用
np.random.permutation(10) .reshape(2, 5)
np.random.seed(1000) # 种子
np.random.normal(2,3,[5,2]) # 高斯分布,其他分布可查
# http://docs.scipy.org/doc/numpy-1.10.1/reference/routines.random.html
np.random.seed(12345678)
x = scipy.stats.norm.rvs(loc=5, scale=3, size=100) # 另外scipy也有这些随机数的生成,附带检验
scipy.stats.shapiro(x)
# http://docs.scipy.org/doc/scipy-0.17.0/reference/stats.html

17 gather和spread

 1 # gather:
 2 def gather( df, key, value, cols ):
 3     id_vars = [ col for col in df.columns if col not in cols ]
 4     id_values = cols
 5     var_name = key
 6     value_name = value
 7     return pandas.melt( df, id_vars, id_values, var_name, value_name )
 8 # 以上是定义的一个函数,实际上一样的,横变竖,是gather,竖变横,是spread
 9 pd.melt(df, id_vars=['E','F'], value_vars=['A','C'])
10 # spread:
11 pd.pivot(df["D"],df["E"],df['F']) #这个是竖变横
12 df3=pd.pivot(df2['D'],df2['variable'],df2['value'])
13 df3.reset_index(level=0, inplace=True) # 再变回df的样子
18 熵

1 scipy.stats.entropy(np.arange(10)) 

19 字符串拼接

1 [",".join(['a','b','d'])]
2 df[['E','F']].groupby('F')['E'].apply(lambda x: "{%s}" % ', '.join(x)) # 分组拼接,前提是这些列都要是字符串
3 df[['E','F']].applymap(str).groupby('E')['F'].apply(lambda x: "%s" % ', '.join(x)) # 所以可以这样
20 随机字符串生成

1 import random,string
2 df2 = pd.DataFrame(range(10),columns=['y'])
3 df2["x"] = [",".join(random.sample(string.lowercase,random.randint(2,5))) for i in range(10)]
21 分列后生成hash表

1 # 用20 的示例数据
2 df3=pd.DataFrame(df2.x.str.split(',').tolist(),index=df2.y).stack().reset_index(level=0)
3 df3.columns=["y","x"]
22 去重
1 df[["F","E"]].drop_duplicates()
23 离散化
1 pd.cut(df.A,range(-1,2,1))

 

 

posted on 2016-05-03 18:09  大饼丸  阅读(4382)  评论(0编辑  收藏  举报

导航