Converts a python object, i.e. a app's output, to a dataframe NOTE - this returns a new DF each time
(value: Any)
| 166 | |
| 167 | |
| 168 | def to_df(value: Any) -> pd.DataFrame: |
| 169 | """ |
| 170 | Converts a python object, i.e. a app's output, to a dataframe |
| 171 | NOTE - this returns a new DF each time |
| 172 | """ |
| 173 | if value is None: |
| 174 | # This return the empty dataframe, which atm is the same as |
| 175 | # the empty file object in the CAS. |
| 176 | # However this is not ensured as pyarrow changes |
| 177 | return pd.DataFrame() |
| 178 | |
| 179 | if isinstance(value, pd.DataFrame): |
| 180 | return value.copy(deep=True) |
| 181 | |
| 182 | if isinstance(value, (pd.Series, pd.Index)): |
| 183 | if value.name is not None: |
| 184 | return pd.DataFrame(value) |
| 185 | |
| 186 | return pd.DataFrame({"Result": value}) |
| 187 | |
| 188 | if isinstance(value, (Number, str, bool, datetime.datetime, datetime.timedelta)): |
| 189 | return pd.DataFrame({"Result": value}, index=[0]) |
| 190 | |
| 191 | if isinstance(value, np.ndarray): |
| 192 | try: |
| 193 | out_df = pd.DataFrame(value) |
| 194 | except ValueError: |
| 195 | squeezed = np.squeeze(value) |
| 196 | if squeezed.shape == (): |
| 197 | # must be a scalar |
| 198 | out_df = pd.DataFrame({"Result": squeezed}, index=[0]) |
| 199 | else: |
| 200 | out_df = pd.DataFrame(squeezed) |
| 201 | |
| 202 | if out_df.columns.tolist() == [0]: |
| 203 | out_df.columns = ["Result"] |
| 204 | |
| 205 | return out_df |
| 206 | |
| 207 | raise ValueError("Must return a primitive, pd.DataFrame, pd.Series or numpy array.") |
| 208 | |
| 209 | |
| 210 | TRUNCATE_CELLS = 10000 |