CHARLS_NL.py 887 B

123456789101112131415161718192021
  1. import pandas as pd
  2. #读取CHARLS数据
  3. CHARLS_data = pd.read_csv("CHARLS_data_pollutants.csv")
  4. #读取夜光数据
  5. pollutants_data = pd.read_csv("night_light_result.csv", encoding="utf-8")
  6. #处理哪一年的数据
  7. year = 2020
  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_pollutants.csv",index=False)
  19. print(year)