pandas实例-Stats-US_Baby_Names

2020-05-12  本文已影响0人  橘猫吃不胖

继续前面的练习,之前的文章参考:


先来看看我们的数据集

df = pd.read_csv('https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/06_Stats/US_Baby_Names/US_Baby_Names_right.csv')

df.head()

哇,这次居然有100多万条记录

1. Delete the column 'Unnamed: 0' and 'Id'

删除两列
删除的话,通过我们之前的筛选也是可以实现的,或者使用专门的删除函数
参考:pandas删除函数-drop

df.drop(columns=['Unnamed: 0' , 'Id'] , inplace=True)

2. Are there more male or female names in the dataset?

这个是想看看性别的分布情况
我们可以使用聚合函数,或者

df.groupby('Gender')['Gender'].count()

df['Gender'].value_counts()

顺便看个占比好了

df.groupby('Gender')['Gender'].count() / df['Gender'].count()

3. Group the dataset by name and assign to names

根据name做一个聚合

df.groupby('Name')['Count'].sum().sort_values(ascending=False).head()

这里注意一个问题,就是这个聚合的时候,需要使用字段Count,我一开始还以为作者写错了,为什么要用sum,我就直接根据name做count了,后来才明白

4. How many different names exist in the dataset?

一共有多少个名字呢?

df['Name'].nunique()

5. What is the name with most occurrences?

出现次数最多的名字

df_name = df.groupby('Name')['Count'].sum()
df_name.sort_values(ascending=False).head(1)

首先想到的是这种方式,但是还有一种更简单的方式,之前也用过,但是我给忘记了

参考:pandas-idxmin和idxmax

这个函数,比较方便

df_name.idxmax()

6. How many different names have the least occurrences?

这个题目,我还是思考了一下,上一题是需要看对应的名字,而这一题是需要看所有的名字,说明不止一个

df_name[df_name==df_name.min()].count()

7. What is the median name occurrence?

这一题和上一题类似,这次是看中位数

df_name[df_name==df_name.median()]

8. Get a summary with the mean, min, max, std and quartiles.

这个要使用最常用的函数describe就行了

df_name.describe()
上一篇 下一篇

猜你喜欢

热点阅读