|
a |
|
b/inmoose/utils/factor.py |
|
|
1 |
# ----------------------------------------------------------------------------- |
|
|
2 |
# Copyright (C) 2022-2023 M. Colange |
|
|
3 |
|
|
|
4 |
# This program is free software: you can redistribute it and/or modify |
|
|
5 |
# it under the terms of the GNU General Public License as published by |
|
|
6 |
# the Free Software Foundation, either version 3 of the License, or |
|
|
7 |
# (at your option) any later version. |
|
|
8 |
|
|
|
9 |
# This program is distributed in the hope that it will be useful, |
|
|
10 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
|
11 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
|
12 |
# GNU General Public License for more details. |
|
|
13 |
|
|
|
14 |
# You should have received a copy of the GNU General Public License |
|
|
15 |
# along with this program. If not, see <https://www.gnu.org/licenses/>. |
|
|
16 |
# ----------------------------------------------------------------------------- |
|
|
17 |
|
|
|
18 |
|
|
|
19 |
from pandas import Categorical |
|
|
20 |
|
|
|
21 |
|
|
|
22 |
class Factor(Categorical): |
|
|
23 |
""" |
|
|
24 |
A class to represent a factor, as in R. |
|
|
25 |
|
|
|
26 |
It is essentially a :obj:`pandas.Categorical` object, with additional |
|
|
27 |
methods to mimic R API. |
|
|
28 |
""" |
|
|
29 |
|
|
|
30 |
def __init__(self, arr): |
|
|
31 |
""" |
|
|
32 |
Constructs a Factor instance from an array |
|
|
33 |
|
|
|
34 |
Arguments |
|
|
35 |
--------- |
|
|
36 |
arr : array_like |
|
|
37 |
a list of factors |
|
|
38 |
""" |
|
|
39 |
|
|
|
40 |
super().__init__(arr) |
|
|
41 |
|
|
|
42 |
def droplevels(self): |
|
|
43 |
""" |
|
|
44 |
drop unused levels |
|
|
45 |
""" |
|
|
46 |
|
|
|
47 |
return Factor(self.__array__()) |
|
|
48 |
|
|
|
49 |
def nlevels(self): |
|
|
50 |
""" |
|
|
51 |
the number of levels |
|
|
52 |
""" |
|
|
53 |
|
|
|
54 |
return len(self.categories) |
|
|
55 |
|
|
|
56 |
|
|
|
57 |
def asfactor(g): |
|
|
58 |
if type(g) is Factor: |
|
|
59 |
return g |
|
|
60 |
else: |
|
|
61 |
return Factor(g) |
|
|
62 |
|
|
|
63 |
|
|
|
64 |
def gl(n, k): |
|
|
65 |
arr = [] |
|
|
66 |
for i in range(1, n + 1): |
|
|
67 |
arr.extend([i for j in range(k)]) |
|
|
68 |
return Factor(arr) |