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

 

 

转载于:https://www.cnblogs.com/big-face/p/5455983.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值