pandas 使用指定的排序重新排序分类变量?

2guxujil  于 2023-04-10  发布在  其他
关注(0)|答案(1)|浏览(130)

我有一个X_train数据框。其中一列locale具有唯一值:['Regional', 'Local', 'National'].
我尝试将此列变成一个有序分类变量,正确的顺序是从最小到最大:['Local', 'Regional', 'National'] = [0, 1, 2]
然而,它是不工作.是的,我看到了类似的问题,我的其他线程,但这些解决方案不工作.我使用factorize,但开放的定制顺序LabelEncoder太,如果该选项现在存在.
这是我的代码:

print(X_train['locale'][:10])
cat = pd.Categorical(X_train['locale'], categories = ['Local', 'Regional', 'National'])
codes, uniques = pd.factorize(cat)
print(codes[:10])

输出:(如果全部为国家,则应为2)

X列 Dataframe (_T):

{'id': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4},
 'date': {0: Timestamp('2013-01-01 00:00:00'),
  1: Timestamp('2013-01-01 00:00:00'),
  2: Timestamp('2013-01-01 00:00:00'),
  3: Timestamp('2013-01-01 00:00:00'),
  4: Timestamp('2013-01-01 00:00:00')},
 'store_nbr': {0: '1', 1: '1', 2: '1', 3: '1', 4: '1'},
 'family': {0: 'AUTOMOTIVE',
  1: 'BABY CARE',
  2: 'BEAUTY',
  3: 'BEVERAGES',
  4: 'BOOKS'},
 'sales': {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0},
 'onpromotion': {0: 0, 1: 0, 2: 0, 3: 0, 4: 0},
 'city': {0: 'Quito', 1: 'Quito', 2: 'Quito', 3: 'Quito', 4: 'Quito'},
 'state': {0: 'Pichincha',
  1: 'Pichincha',
  2: 'Pichincha',
  3: 'Pichincha',
  4: 'Pichincha'},
 'store_type': {0: 'D', 1: 'D', 2: 'D', 3: 'D', 4: 'D'},
 'cluster': {0: '13', 1: '13', 2: '13', 3: '13', 4: '13'},
 'dcoilwtico': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan},
 'transactions': {0: nan, 1: nan, 2: nan, 3: nan, 4: nan},
 'holiday_type': {0: 'Holiday',
  1: 'Holiday',
  2: 'Holiday',
  3: 'Holiday',
  4: 'Holiday'},
 'locale': {0: 'National',
  1: 'National',
  2: 'National',
  3: 'National',
  4: 'National'},
 'locale_name': {0: 'Ecuador',
  1: 'Ecuador',
  2: 'Ecuador',
  3: 'Ecuador',
  4: 'Ecuador'},
 'description': {0: 'Primer dia del ano',
  1: 'Primer dia del ano',
  2: 'Primer dia del ano',
  3: 'Primer dia del ano',
  4: 'Primer dia del ano'},
 'transferred': {0: False, 1: False, 2: False, 3: False, 4: False},
 'year': {0: '2013', 1: '2013', 2: '2013', 3: '2013', 4: '2013'},
 'month': {0: '1', 1: '1', 2: '1', 3: '1', 4: '1'},
 'week': {0: '1', 1: '1', 2: '1', 3: '1', 4: '1'},
 'quarter': {0: '1', 1: '1', 2: '1', 3: '1', 4: '1'},
 'day_of_week': {0: 'Tuesday',
  1: 'Tuesday',
  2: 'Tuesday',
  3: 'Tuesday',
  4: 'Tuesday'}}
lmvvr0a8

lmvvr0a81#

使用

print(cat.codes)

使用pd.factorize()重构列,标签的顺序可能与最初创建分类时的顺序不同。
More documentation

相关问题