CHARLS_NL.py 954 B

1234567891011121314151617181920
  1. import pandas as pd
  2. years = [2011, 2013,2015, 2018, 2020]
  3. #读取夜光数据
  4. pollutants_data = pd.read_csv("night_light_result.csv", encoding="utf-8")
  5. for year in years:
  6. #读取CHARLS数据
  7. CHARLS_data = pd.read_csv("CHARLS_data_pollutants.csv")
  8. #新增两列,分别为year的去年和前年的环境值
  9. # CHARLS_data[['last_year_pm2.5', "before_last_pm2.5"]]=''
  10. #开始筛选出year的数据
  11. CHARLS_data_year = CHARLS_data[CHARLS_data['wave']==year]
  12. #两个表合并
  13. table_merge = pd.merge(CHARLS_data_year, pollutants_data, left_on="city", right_on="ext_name", how='left')
  14. # table_merge_last.to_csv("123.csv",index=False)
  15. #更新CHARLS表
  16. CHARLS_data.loc[CHARLS_data['wave']==year, 'last_year_nl'] = table_merge[str(year-1)].values
  17. CHARLS_data.loc[CHARLS_data['wave']==year, 'before_last_nl'] = table_merge[str(year-2)].values
  18. CHARLS_data.to_csv("CHARLS_data_p_n.csv",index=False)
  19. print(year)