Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add didiers to_records method #5588

Merged
merged 6 commits into from
Oct 30, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading