基于新西兰社区数据生成新列后Date列丢失问题求助
问题:合并数据后日期列丢失,且需按区域+年份计算均值
我正尝试基于名为“community data”的数据集创建两个新列,数据集包含新西兰不同区域的Dep_Index(剥夺指数)和AU_GMP_PER_CAPITA(人均博彩支出)字段,这些参数与各区域(AU2017_name列)及数据采集日期相关。
需要创建的两个新列:
- 特定区域特定年份(如2013年)的
Dep_Index均值; - 特定区域特定年份的
AU_GMP_PER_CAPITA均值。
数据集快照
| AU2017_code | Date | AU_GMP_PER_CAPITA | Dep_Index | AU2017_name | TA2018_name | TALB |
|---|---|---|---|---|---|---|
| 500100 | 1/03/2013 | 62.73254111 | 9 | Awanui | Far North District | Far North District |
| 500202 | 1/03/2013 | 12.1231307 | 9 | Karikari Peninsula-Maungataniwha | Far North District | Far North District |
| 500203 | 1/03/2013 | 151.8410144 | 9 | Taipa Bay-Mangonui | Far North District | Far North District |
| 500204 | 1/03/2013 | 56.46501065 | 8 | Herekino | Far North District | Far North District |
| 500205 | 1/03/2013 | 0 | 9 | Ahipara | Far North District | Far North District |
| 500206 | 1/03/2013 | 0 | 10 | North Cape | Far North District | Far North District |
| 500207 | 1/03/2013 | 0 | 9 | Houhora | Far North District | Far North District |
| 500208 | 1/03/2013 | 65.58023849 | 8 | Motutangi-Kareponia | Far North District | Far North District |
| 500301 | 1/03/2013 | 197.2491364 | 10 | Kaitaia West | Far North District | Far North District |
| 500302 | 1/03/2013 | 206.8280015 | 10 | Kaitaia East | Far North District | Far North District |
| 500401 | 1/03/2013 | 0 | 10 | Kaeo | Far North District | Far North District |
| 500402 | 1/03/2013 | 0 | 9 | Mangapa-Matauri Bay | Far North District | Far North District |
| 500500 | 1/03/2013 | 22.96812827 | 10 | Kohukohu | Far North District | Far North District |
| 500600 | 1/03/2013 | 100.051763 | 10 | Rawene | Far North District | Far North District |
| 500700 | 1/03/2013 | 196.8465345 | 10 | Omapere and Opononi | Far North District | Far North District |
| 500801 | 1/03/2013 | 3.170242784 | 10 | Hokianga North | Far North District | Far North District |
| 500802 | 1/03/2013 | 18.68430235 | 10 | Hokianga South | Far North District | Far North District |
| 500900 | 1/03/2013 | 70.01595188 | 7 | Kerikeri | Far North District | Far North District |
| 501000 | 1/03/2013 | 151.5078577 | 6 | Russell | Far North District | Far North District |
| 501100 | 1/03/2013 | 187.1490424 | 8 | Paihia | Far North District | Far North District |
| 501200 | 1/03/2013 | 73.15790271 | 7 | Haruru Falls | Far North District | Far North District |
| 501300 | 1/03/2013 | 78.61958836 | 5 | Opua East | Far North District | Far North District |
| 501400 | 1/03/2013 | 390.1053264 | 10 | Kawakawa | Far North District | Far North District |
| 501500 | 1/03/2013 | 193.069158 | 10 | Moerewa | Far North District | Far North District |
问题描述
我编写了Python代码,但运行后最终输出中的Date列丢失了,尽管已经将Date列设为索引。原代码如下:
import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn as sns #load the community data csv as a pandas dataframe community_data = pd.read_csv('community data.csv') # strip whitespaces from column headers community_data.columns = [col.strip() for col in community_data.columns] #Convert Date column from object to Datetime format community_data['Date'] = pd.to_datetime(community_data['Date']) # Set the 'Date' column as index community_data.set_index('Date', inplace=True) # Filter data for the specified years community_Data_years = community_data[community_data.index.year.isin([2013,2014,2015,2016,2017,2018,2019,2020])] # Calculate average Dep_Index for each AU2017_name for all unique years avg_dep_index = community_Data_years.groupby('AU2017_name')['Dep_Index'].mean().reset_index() avg_dep_index = avg_dep_index.rename(columns={'Dep_Index':'Avg_Dep_Index'}) community_data = pd.merge(community_data, avg_dep_index, on='AU2017_name', how='left') # Calculate average AU_GMP_PER_CAPITA for each AU2017_name for all unique years avg_GMP_index = community_Data_years.groupby('AU2017_name')['AU_GMP_PER_CAPITA'].mean().reset_index() avg_GMP_index = avg_GMP_index.rename(columns={'AU_GMP_PER_CAPITA':'AVG_GMP'}) community_data = pd.merge(community_data, avg_GMP_index, on='AU2017_name', how='left') #preview output community_data.head()
解决方案
问题原因
- Date列丢失:
pd.merge默认仅基于DataFrame的列进行合并,索引不会自动转为列保留,因此将Date设为索引后,合并时索引会被丢弃。 - 均值计算不符合需求:原代码仅按区域计算所有年份的均值,而非特定区域+特定年份的均值。
修正后的代码
import pandas as pd # 加载数据集 community_data = pd.read_csv('community data.csv') # 去除列名中的空格 community_data.columns = [col.strip() for col in community_data.columns] # 将Date列转换为日期格式 community_data['Date'] = pd.to_datetime(community_data['Date']) # 提取年份作为单独列,用于按区域+年份分组 community_data['Year'] = community_data['Date'].dt.year # 筛选指定年份的数据 filtered_data = community_data[community_data['Year'].isin([2013,2014,2015,2016,2017,2018,2019,2020])] # 按区域+年份计算Dep_Index的均值 avg_dep_year = filtered_data.groupby(['AU2017_name', 'Year'])['Dep_Index'].mean().reset_index() avg_dep_year.rename(columns={'Dep_Index': 'Avg_Dep_Index_Year'}, inplace=True) # 按区域+年份计算AU_GMP_PER_CAPITA的均值 avg_gmp_year = filtered_data.groupby(['AU2017_name', 'Year'])['AU_GMP_PER_CAPITA'].mean().reset_index() avg_gmp_year.rename(columns={'AU_GMP_PER_CAPITA': 'Avg_GMP_Year'}, inplace=True) # 合并数据,保留原始Date列,确保均值与对应区域、年份匹配 community_data = pd.merge(community_data, avg_dep_year, on=['AU2017_name', 'Year'], how='left') community_data = pd.merge(community_data, avg_gmp_year, on=['AU2017_name', 'Year'], how='left') # 查看结果 community_data.head()
关键修正点
- 新增
Year列,明确按区域+年份分组,满足“特定区域特定年份”的均值计算需求; - 不将Date设为索引,避免合并操作时丢失日期信息;
- 合并时使用
AU2017_name和Year作为关联键,确保每个区域每年的均值正确匹配到原始数据行; - 最终结果保留了原始的Date列,同时新增了两个符合需求的均值列。
另一种临时修复(保留索引方式)
如果一定要保留Date作为索引的写法,可在合并前将索引转为普通列:
# 在merge前添加这行代码,把Date索引转为列 community_data = community_data.reset_index()
但这种方式不如直接保留Date列并提取年份的写法清晰,尤其不利于后续按年份分析。
内容的提问来源于stack exchange,提问作者YShastri
相关产品推荐
相关产品推荐

