一、问题揪出:

File “/usr/share/anaconda3/envs/tf2.0-gpu/lib/python3.7/site-packages/pandas/core/frame.py”, line 2906, in getitem
indexer = self.columns.get_loc(key)
File “/usr/share/anaconda3/envs/tf2.0-gpu/lib/python3.7/site-packages/pandas/core/indexes/base.py”, line 2897, in get_loc
raise KeyError(key) from err
KeyError: ‘sex’

二、解决措施:

发现报错定位在,nums[col] = int(data[col].max())
经过发现,是因为 sparse_column,中的字段中,在data.columns中没有出现
将字段调整后代码与之相对应的 sparse_col 字段,即可运行

此刻将代码改成如下即可运行,亲测有效,以下为验证过程记录:

import pandas as pddata = pd.read_csv('data.csv')sparse_col = ['sex', 'age']nums = {}print("data.columns:", data.columns)#data.columns: Index(['user_no', 'sex', 'age'], dtype='object')print("sparse_col:", sparse_col)#sparse_col: ['sex', 'age']for col in sparse_col:print("col:", col)#col: sex#col: agenums[col]= int(data[col].max())#nums {'sex': 1, 'age': 18}print('nums', nums)#nums {'sex': 1, 'age': 18}