Returns the rows I from the data set X For a single index, the result is as follows: * 1xM matrix in case of scipy sparse NxM matrix X * pandas series in case of a pandas data frame * row in case of list or numpy format
(
X: modALinput, I: Union[int, List[int], np.ndarray]
)
| 87 | |
| 88 | |
| 89 | def retrieve_rows( |
| 90 | X: modALinput, I: Union[int, List[int], np.ndarray] |
| 91 | ) -> Union[sp.csc_matrix, np.ndarray, pd.DataFrame]: |
| 92 | """ |
| 93 | Returns the rows I from the data set X |
| 94 | |
| 95 | For a single index, the result is as follows: |
| 96 | * 1xM matrix in case of scipy sparse NxM matrix X |
| 97 | * pandas series in case of a pandas data frame |
| 98 | * row in case of list or numpy format |
| 99 | """ |
| 100 | |
| 101 | try: |
| 102 | return X[I] |
| 103 | except: |
| 104 | if sp.issparse(X): |
| 105 | # Out of the sparse matrix formats (sp.csc_matrix, sp.csr_matrix, sp.bsr_matrix, |
| 106 | # sp.lil_matrix, sp.dok_matrix, sp.coo_matrix, sp.dia_matrix), only sp.bsr_matrix, sp.coo_matrix |
| 107 | # and sp.dia_matrix don't support indexing and need to be converted to a sparse format |
| 108 | # that does support indexing. It seems conversion to CSR is currently most efficient. |
| 109 | |
| 110 | sp_format = X.getformat() |
| 111 | return X.tocsr()[I].asformat(sp_format) |
| 112 | elif isinstance(X, pd.DataFrame): |
| 113 | return X.iloc[I] |
| 114 | elif isinstance(X, list): |
| 115 | return np.array(X)[I].tolist() |
| 116 | elif isinstance(X, dict): |
| 117 | X_return = {} |
| 118 | for key, value in X.items(): |
| 119 | X_return[key] = retrieve_rows(value, I) |
| 120 | return X_return |
| 121 | |
| 122 | raise TypeError("%s datatype is not supported" % type(X)) |
| 123 | |
| 124 | |
| 125 | def drop_rows( |