科技工作者心理健康分析

python数据分析实战案例

项目名称:科技工作者心理健康分析

项目分析数据:https://www.kaggle.com/osmi/mental-health-in-tech-survey

需求一:统计各国家男性女性心理健康数据分布

代码

# -*- coding: utf-8 -*-

"""
    项目名称:科技工作者心理健康数据分析 (Mental Health in Tech Survey)
"""
import csv

# 数据集路径
data_path = './survey.csv'


def run_main():
	"""
		主函数
	"""
	male_set = {'male', 'm'}  # “男性”可能的取值
	female_set = {'female', 'f'}  # “女性”可能的取值

	# 构造统计结果的数据结构 result_dict
	# 其中每个元素是键值对,“键”是国家名称,“值”是列表结构,
	# 列表的第一个数为该国家女性统计数据,第二个数为该国家男性统计数据
	# 如 {'United States': [20, 50], 'Canada': [30, 40]}
	# 思考:这里的“值”为什么用列表(list)而不用元组(tuple)
	result_dict = {}

	with open(data_path, 'r', newline='') as csvfile:
		# 加载数据
		rows = csv.reader(csvfile)
		for i, row in enumerate(rows):
			if i == 0:
				# 跳过第一行表头数据
				continue

			if i % 50 == 0:
				print('正在处理第{}行数据...'.format(i))

			gender_val = row[2] # 性别数据
			country_val = row[3] # 国家数据

			# 去掉可能存在的空格
			gender_val = gender_val.replace(' ', '')
			# 转换为小写
			gender_val = gender_val.lower()

			# 判断“国家”是否已经存在
			if country_val not in result_dict:
				# 如果不存在,初始化数据
				# 第一个参数存储女性的人数, 第二个参数存储男性的人数
				result_dict[country_val] = [0, 0]

			# 判断性别
			if gender_val in female_set:
				# 女性
				result_dict[country_val][0] += 1
			elif gender_val in male_set:
				# 男性
				result_dict[country_val][1] += 1
			else:
				# 噪声数据,不做处理
				pass

	# 将结果写入文件
	with open('gender_country.csv', 'w', newline='', encoding='utf-8') as csvfile:
		csvwriter = csv.writer(csvfile, delimiter=',')
		# 写入表头
		csvwriter.writerow(['国家', '男性', '女性'])

		# 写入统计结果
		for k, v in list(result_dict.items()):
			csvwriter.writerow([k, v[0], v[1]])


if __name__ == '__main__':
	run_main()

数据结果

国家,男性,女性
United States,172,549
Canada,14,55
United Kingdom,25,153
Bulgaria,1,3
France,0,13
Portugal,0,2
Netherlands,3,24
Switzerland,1,6
Poland,1,6
Australia,5,16
Germany,1,42
Russia,0,2
Mexico,0,3
Brazil,0,6
Slovenia,0,1
Costa Rica,0,1
Austria,0,3
Ireland,4,23
India,2,8
South Africa,1,5
Italy,0,5
Sweden,2,5
Colombia,0,2
Latvia,0,1
Romania,0,1
Belgium,2,4
New Zealand,1,7
Zimbabwe,0,0
Spain,1,0
Finland,0,3
Uruguay,0,1
Israel,1,4
Bosnia and Herzegovina,0,1
Hungary,1,0
Singapore,0,4
Japan,0,1
Nigeria,0,1
Croatia,0,2
Norway,0,1
Thailand,0,1
Denmark,0,2
"Bahamas, The",0,0
Greece,0,2
Moldova,0,1
Georgia,0,1
China,0,1
Czech Republic,0,1
Philippines,0,1

需求二:统计各个国家存在的心理健康问题的平均年龄

分析步骤

  1. 先找到有心理问题的记录中的年龄数据,然后根据国家列出所有符合条件的年龄集合;

  2. 将年龄相加除以有心理健康问题的人数;

脏数据,发现Zimbabwe国家的年龄数据是999999,直接过滤掉了

代码

# -*- coding: utf-8 -*-

"""
    项目名称:科技工作者心理健康数据分析 (Mental Health in Tech Survey)
"""
import csv

# 数据集路径
data_path = './survey.csv'


def run_main():
   mental_health_set = {'Yes'}  # 心理健康问题要找到的值

   result_dict = {}  # 最终结果存放列表

   with open(data_path, 'r', newline='') as csvfile:
      # 加载数据
      rows = csv.reader(csvfile)

      for i, row in enumerate(rows):
         if i == 0:
            # 跳过第一行表头数据
            continue

         if i % 50 == 0:
            print('正在处理第{}行数据...'.format(i))

         age_val = row[1]  # 年龄数据
         country_val = row[3]  # 国家数据
         mental_health_val = row[18]  # 是否有心理问题

         # 去掉可能存在的空格
         age_val = age_val.replace(' ', '')
         mental_health_val = mental_health_val.replace(' ', '')

         # 判断“国家”是否已经存在
         if country_val not in result_dict:
            # 如果不存在,初始化数据
            # 第一个参数存储符合条件的年龄总和, 第二个参数存储有多少条记录 第三个参数存储平均年龄
            result_dict[country_val] = [0, 0, 0]

         # 过滤 有心理问题的, 不合常理的数据,如Zimbabwe 年龄999999 392行
         if mental_health_val in mental_health_set and (len(age_val) <= 3):
            result_dict[country_val][0] += int(age_val)
            result_dict[country_val][1] += 1
         else:
            # 噪声数据,不做处理
            pass

   # 将结果写入文件
   with open('mental_country.csv', 'w', newline='', encoding='utf-8') as csvfile:
      csvwriter = csv.writer(csvfile, delimiter=',')
      # 写入表头
      csvwriter.writerow(['国家', '年龄'])

      # 写入统计结果
      for k, v in list(result_dict.items()):
         # 处理年龄为0的所属国家记录(有心理问题的, 不合常理的数据)
         if int(v[0]) == 0:
            v[2] = 0
         else:
            # 平均年龄
            v[2] = int(v[0] / v[1])

         csvwriter.writerow([k, v[2]])


if __name__ == '__main__':
   run_main()

数据结果

国家,年龄
United States,33
Canada,29
United Kingdom,31
Bulgaria,26
France,26
Portugal,27
Netherlands,33
Switzerland,30
Poland,0
Australia,31
Germany,32
Russia,28
Mexico,0
Brazil,0
Slovenia,19
Costa Rica,0
Austria,0
Ireland,35
India,24
South Africa,61
Italy,37
Sweden,0
Colombia,26
Latvia,0
Romania,0
Belgium,30
New Zealand,36
Zimbabwe,0
Spain,30
Finland,27
Uruguay,0
Israel,27
Bosnia and Herzegovina,0
Hungary,27
Singapore,39
Japan,49
Nigeria,0
Croatia,43
Norway,0
Thailand,0
Denmark,0
"Bahamas, The",8
Greece,36
Moldova,0
Georgia,20
China,0
Czech Republic,0
Philippines,31

猜你喜欢

转载自blog.csdn.net/qq_14993591/article/details/83044834