Pandas 数据处理:从数据加载到统计分析
导入 Pandas 库
import pandas as pd
1. 数据加载与初步探索
读取 Excel 文件到 DataFrame
#============================= show me your code ======================= df = pd.read_excel('employees.xlsx')
打印后 4 行数据的信息
#============================= show me your code ======================= tail4 = df.tail(4) print('后 4 行数据:') print(tail4)
数值型数据的主要统计信息
#============================= show me your code ======================= df_num = df.describe() df_obj = df.describe(include='object') print('数值型数据的主要统计信息:') print(df_num) print('类别型数据的主要统计信息:') print(df_obj)
print('-' * 80)
2. 数据选择与过滤
筛选技术部门员工的所有信息
#============================= show me your code ======================= tech_df = df[df['department'] == '技术部'] print('技术部门员工的所有信:') print(tech_df)
筛选 2019 年入职员工,展示其所有信息
#============================= show me your code ======================= df_2019 = df[df['start_date'] == 2019] print('2019 年入职员工信息:') print(df_2019)
筛选薪资在 15000-20000 之间 (两端都包含)
#============================= show me your code ======================= sal_df = df[(df['salary'] >= 15000) & (df['salary'] <= 20000)] print('薪资在 15000-20000 之间的员工信息:') print(sal_df)
print('-' * 80)
3. 计算
根据入职时间计算员工的工作年限(当前年份-入职年份),并设为新的一列。
#============================= show me your code ======================= df['work_years'] = pd.Timestamp.now().year - df['start_date'].dt.year print('添加工作年限列后的数据:') print(df)
对入职年限高于 5 年的员工,加薪 10%
#============================= show me your code =======================
代码
print('特定员工加薪 10% 后的数据:') print(df)
print('-' * 80)
4. 数据统计与分组
按部门分组,平均薪资和年龄
#============================= show me your code ======================= mean_sal_age = df.groupby('department').agg({'salary': 'mean', 'age': 'mean'}) print('各部门的平均薪资和年龄:') print(mean_sal_age)
print('-' * 80)
5. 问题回答
工作年限小于 2 年的员工中,年薪最低的员工属于哪个部门
#============================= show me your code ======================= filtered_df = df[df['work_years'] < 2] min_sal_dept = filtered_df[filtered_df['salary'] == filtered_df['salary'].min()]['department'].values[0] print(f'工作年限小于 2 年的员工中年薪最低员工所在部门:{min_sal_dept}')
年薪最高的员工比最低的员工年长几岁
#============================= show me your code ======================= age_diff = df[df['salary'].idxmax()]['age'] - df[df['salary'].idxmin()]['age'] print(f'年薪最高的员工比最低的员工年长 {age_diff} 岁') KeyError Traceback (most recent call last) /opt/conda/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_value(self, series, key) 3117 return self._engine.get_value(s, k, -> 3118 tz=getattr(series.dtype, 'tz', None)) 3119 except KeyError as e1:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
KeyError: 8
During handling of the above exception, another exception occurred:
IndexError Traceback (most recent call last)
/opt/conda/lib/python3.6/site-packages/pandas/core/series.py in getitem(self, key) 765 key = com._apply_if_callable(key, self) 766 try: --> 767 result = self.index.get_value(self, key) 768 769 if not is_scalar(result):
/opt/conda/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_value(self, series, key) 3122 3123 try: -> 3124 return libindex.get_value_box(s, key) 3125 except IndexError: 3126 raise
pandas/_libs/index.pyx in pandas._libs.index.get_value_box()
pandas/_libs/index.pyx in pandas._libs.index.get_value_box()
IndexError: index out of bounds
这个问题怎么修改内容:在给定的代码中,出现了一个索引错误(IndexError),因为在计算min_sal_dept时使用了一个无效的索引。这是因为在没有筛选工作年限小于2年的员工之前,尝试访问最低工资的行。
为了解决这个问题,您可以在计算最低工资之前,先筛选出工作年限小于2年的员工。下面是修改后的代码:
# 工作年限小于2年的员工中,年薪最低的员工属于哪个部门
#============================= show me your code =======================
filtered_df = df[df['work_years'] < 2]
min_sal_dept = filtered_df[filtered_df['salary'] == filtered_df['salary'].min()]['department'].values[0]
print(f'工作年限小于2年的员工中年薪最低员工所在部门:{min_sal_dept}')
请注意,我们首先筛选出工作年限小于2年的员工,并将其存储在filtered_df中。然后,我们在filtered_df上查找年薪最低的员工所在的部门,并通过.values[0]获取该部门的值。这样可以避免索引错误并正确地找到年薪最低的员工所在的部门。
希望这可以帮助到您!
原文地址: http://www.cveoy.top/t/topic/z4g 著作权归作者所有。请勿转载和采集!