我收到一個錯誤:
<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's 也在填充列而不是我映射到原始值的值。
怎么辦呢?我也嘗試使用locand ilocas data.loc[:,'month'] = data.loc[:,'month'].map()ordata.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)
uj5u.com熱心網友回復:
無需映射。
日期和日期時間在 python 中有詳細的介紹。將每個月的第一個字母大寫,然后將其強制為日期時間。下面的代碼
df['month'] =pd.to_datetime(data['month'].str.capitalize(), format='%b').dt.month
uj5u.com熱心網友回復:
你的字典應該有月份作為鍵(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})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/362548.html
上一篇:AttributeError:'Index'物件沒有屬性'replace'
下一篇:從熊貓滾動系列呼叫任意函式
