Skip to content

Commit

Permalink
Add didiers to_records method (#5588)
Browse files Browse the repository at this point in the history
* Add didiers to_records

* unused import

* Bring back polars + do what igor suggested

* Make the output consistent with what it was.

* Black ?

* spelling.  oops.  almost like we have a pre commit or something
  • Loading branch information
jmaslek committed Oct 30, 2023
1 parent d4e2fc8 commit 5c0b856
Showing 1 changed file with 29 additions and 24 deletions.
53 changes: 29 additions & 24 deletions openbb_platform/platform/core/openbb_core/app/model/obbject.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def to_polars(self) -> "PolarsDataFrame":
from polars import from_pandas # pylint: disable=import-outside-toplevel
except ImportError as exc:
raise ImportError(
"Please install polars: `pip install polars` to use this function."
"Please install polars: `pip install polars pyarrow` to use this method."
) from exc

return from_pandas(self.to_dataframe().reset_index())
Expand All @@ -184,36 +184,41 @@ def to_numpy(self) -> ndarray:
"""Convert results field to numpy array."""
return self.to_dataframe().reset_index().to_numpy()

def to_dict(self) -> Dict[str, List]:
"""Convert results field to list of values.
def to_dict(
self,
orient: Literal[
"dict", "list", "series", "split", "tight", "records", "index"
] = "list",
) -> Dict[str, List]:
"""Convert results field to a dictionary using any of pandas to_dict options.
Parameters
----------
orient : Literal["dict", "list", "series", "split", "tight", "records", "index"]
Value to pass to `.to_dict()` method
Returns
-------
Dict[str, List]
Dictionary of lists.
"""
if isinstance(self.results, dict) and all(
isinstance(v, dict) for v in self.results.values()
):
results: Dict[str, List] = {}
for _, v in self.results.items():
for kk, vv in v.items():
if kk not in results:
results[kk] = []
results[kk].append(vv)

return results

df = self.to_dataframe().reset_index() # type: ignore
results = {}
for field in df.columns:
f = df[field].tolist()
results[field] = f[0] if len(f) == 1 else f

# remove index from results
if "index" in results:
df = self.to_dataframe() # type: ignore
transpose = False
if orient == "list":
transpose = True
if not isinstance(self.results, dict):
transpose = False
else: # Only enter the loop if self.results is a dictionary
for key, value in self.results.items():
if not isinstance(value, dict):
transpose = False
break
if transpose:
df = df.T
results = df.to_dict(orient=orient)
if orient == "list" and "index" in results:
del results["index"]

return results

def to_chart(self, **kwargs):
Expand Down

0 comments on commit 5c0b856

Please sign in to comment.