gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:34:50 25 4
gpt4 key购买 nike

我收到一个错误:

<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']

enter image description here

原始数据看起来有值。

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

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

最佳答案

无需映射。

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

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

关于python - Pandas - 通过映射重命名每个级别的分类值时出现 'returning-a-view-versus-a-copy' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70054182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com