Pandas——value_counts&index&to_dict

本文利用Pandas分析大学专业与就业数据,涉及all-ages.csv和recent-grads.csv两个CSV文件。主要内容包括计算Major Categories的就读人数、低薪工作学生占比,以及对比两个数据集的就业率变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文数据是大学专业和就业的信息。有两个csv文件all-ages.csv和recent-grads.csv

  • 主要的属性如下:

Rank - The numerical rank of the major by post-graduation median earnings.
Major_code - The numerical code of the major.
Major - The description of the major.
Major_category - The category of the major.
Total - The total number of people who studied the major.
Men - The number of men who studied the major.
Women - The number of women who studied the major.
ShareWomen - The share of women (from 0 to 1) who studied the major.
Employed - The number of people who studied the major and were employed post-graduation.

  • recent-grads.csv
    这里写图片描述
  • all-ages.csv和这个类似,只是某些列的值不同

Summarizing Major Categories

计算两个数据集中每个Major Categories(每个Major Categories包含多个Major
)的就读的人数。

  • Series.value_counts返回的是该Series对象中独一无二的元素的个数(Returns object containing counts of unique values.)是个Series对象。
print(all_ages['Major_category'].value_counts())
'''
Engineering                            29
Education                              16
Humanities & Liberal Arts              15
Biol
### 将 `word_counts` 换为字典的方法 在 Python 中,可以使用内置的 `dict()` 构造函数将某些可迭代对象换为字典。如果 `word_counts` 是一种支持键值对形式的数据结构(例如列表中的元组),可以直接通过 `dict(word_counts)` 实现换。 以下是具体实现方式: #### 方法一:当 `word_counts` 为包含键值对的列表时 假设 `word_counts` 的格式如下: ```python word_counts = [('apple', 3), ('banana', 2), ('cherry', 5)] ``` 可以通过以下代码将其换为字典: ```python word_dict = dict(word_counts) print(word_dict) # 输出: {'apple': 3, 'banana': 2, 'cherry': 5} ``` 此方法适用于任何由 `(key, value)` 对组成的可迭代对象[^1]。 --- #### 方法二:当 `word_counts` 为其他数据类型时 如果 `word_counts` 来源于 Pandas 数据帧或其他集合类对象,则需先处理成适合的形式再调用 `dict()` 函数。例如,对于 Pandas Series 类型的对象,可通过 `.to_dict()` 方法完成换[^2]。 示例代码如下: ```python import pandas as pd # 假设 word_counts 是一个 Pandas Series df = pd.DataFrame({'words': ['apple', 'banana', 'cherry'], 'counts': [3, 2, 5]}) word_series = df.set_index('words')['counts'] # 使用 to_dict() 进行换 word_dict = word_series.to_dict() print(word_dict) # 输出: {'apple': 3, 'banana': 2, 'cherry': 5} ``` --- #### 方法三:手动构建字典 如果无法直接应用上述两种情况,还可以利用字典推导式来创建目标字典。例如: ```python word_counts = [['apple', 3], ['banana', 2], ['cherry', 5]] word_dict = {item[0]: item[1] for item in word_counts} print(word_dict) # 输出: {'apple': 3, 'banana': 2, 'cherry': 5} ``` 这种方法灵活性较高,尤其适用于复杂嵌套结构的情况[^3]。 --- ### 总结 无论输入的具体形态为何种形式,只要能解析出有效的键值对关系,均能够借助 `dict()` 或其变体成功化为标准字典。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值