類別變量¶
In [2]:
Copied!
import numpy as np
import pandas as pd
import numpy as np
import pandas as pd
In [21]:
Copied!
import random
import random
In [28]:
Copied!
np.random.seed(987)
data = ['A', 'B', 'C']*2
np.random.shuffle(data)
np.random.seed(987)
data = ['A', 'B', 'C']*2
np.random.shuffle(data)
In [29]:
Copied!
data
data
Out[29]:
['B', 'A', 'C', 'C', 'B', 'A']
In [30]:
Copied!
cat = pd.Categorical(data)
cat = pd.Categorical(data)
In [31]:
Copied!
cat
cat
Out[31]:
['B', 'A', 'C', 'C', 'B', 'A'] Categories (3, object): ['A', 'B', 'C']
In [32]:
Copied!
cat.categories
cat.categories
Out[32]:
Index(['A', 'B', 'C'], dtype='object')
In [33]:
Copied!
cat.codes
cat.codes
Out[33]:
array([1, 0, 2, 2, 1, 0], dtype=int8)
In [39]:
Copied!
cat = pd.Categorical(data, ordered=True)
cat = pd.Categorical(data, ordered=True)
In [40]:
Copied!
cat
cat
Out[40]:
['B', 'A', 'C', 'C', 'B', 'A'] Categories (3, object): ['A' < 'B' < 'C']
In [43]:
Copied!
cat = cat.rename_categories(['Bronze','Silver','Gold'])
cat = cat.rename_categories(['Bronze','Silver','Gold'])
In [44]:
Copied!
cat
cat
Out[44]:
['Silver', 'Bronze', 'Gold', 'Gold', 'Silver', 'Bronze'] Categories (3, object): ['Bronze' < 'Silver' < 'Gold']