从pandas_exercises里学到的

前言

github上找的练习pandas的一个项目,记录下学到了啥。

项目
https://github.com/guipsamora/pandas_exercises

下载到本地用Jupyter notebook打开就好啦。

读数据

众所周知,读取数据直接用pandas.read_(table,csv,sql,excel)就好,需要注意的是read_tableread_csv里默认的参数sep并不同,前者是\t,而后者是,

计算占比

计算占比时总会agg两个函数,搞的列名会多一层就很烦:

# 各职业里面男性的占比
def m_num(x):
    return x[x.values=='M'].count()
c = users.groupby('occupation').agg({'gender':['count', m_num]}).droplevel(axis=1, level=0)
c['Male ratio'] = c['m_num'] / c['count']

新学到一个思路就是利用value_counts函数,取两个Series直接计算:

c = users.groupby('occupation').agg({'gender':m_num}).gender
r = c / users.occupation.value_counts()

div函数

# create a data frame and apply count to gender
gender_ocup = users.groupby(['occupation', 'gender']).agg({'gender': 'count'})

# create a DataFrame and apply count for each occupation
occup_count = users.groupby(['occupation']).agg('count')

# divide the gender_ocup per the occup_count and multiply per 100
occup_gender = gender_ocup.div(occup_count, level = "occupation") * 100

如果是 Series 需要添加参数 axis

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值