Pandas - 'returning-a-view-versus-a-copy' 通过映射重命名每个级别的分类值时出错

Pandas - 'returning-a-view-versus-a-copy' error when renaming categorical values at each level by mapping

我收到一个错误:

<ipython-input-309-00fb859fe0ab>:9: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  train_set['month'] = train_set['month'].map({1: 'jan', 2: 'feb', 3: 'mar', 4: 'apr',  5: 'may',

尝试用数值重新分配分类变量的变量时。 Nan 也在填充列,而不是我映射到原始值的值。

人们会怎么做呢?我也尝试使用 lociloc 作为 data.loc[:,'month'] = data.loc[:,'month'].map()data.month = data.month.map() 而不是 data['month'] = data['month'].map() 但都没有用。我使用 UCL 的银行商家数据添加了一个示例来显示我的错误。

例子

# import raw dataset from URL (same as data provided, just put in a git repository for ease)
DATA_URL = 'https://raw.githubusercontent.com/ThamuMnyulwa/bankMarketing/main/bank-additional-full.csv'
raw_dataset = pd.read_csv(DATA_URL, sep=';', skipinitialspace=True, index_col=None)

data = raw_dataset.copy()

# rename variables for masking
data['month'] = data['month'].map({1: 'jan', 2: 'feb', 3: 'mar', 4: 'apr',  5: 'may',
                                           6: 'jun', 7: 'jul', 8: 'aug' ,9: 'sep' ,10: 'oct',
                                          11: 'nov',12: 'dec' })
# print to see error
data['month']

原始数据看起来有值。

>> np.unique(raw_dataset['month'])

array(['apr', 'aug', 'dec', 'jul', 'jun', 'mar', 'may', 'nov', 'oct',
       'sep'], dtype=object)

您的字典应该以月份作为键(jan/feb),以数字作为值!

data['month'] = data['month'].map({'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6, 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12})

不用贴图

python 详细介绍了日期和日期时间。将每个月的第一个字母大写,然后将其强制转换为日期时间。下面的代码

df['month'] =pd.to_datetime(data['month'].str.capitalize(), format='%b').dt.month