Thank you for clarifying! If the goal is to create a DataFrame where:
- The index (or row labels) corresponds to
file values.
- The columns correspond to
pretok values.
- The cell values are the
bytes_gpt2 values.
We can achieve this by reshaping the data into a pivot table format in Polars. Here's how you can do it step-by-step:
Step 1: Flatten the Nested Dictionary
First, we'll flatten the nested dictionary structure into a list of records. This will make it easier to work with in Polars.
flattened_data = [
{"file": file, "pretok": pretok, "bytes_gpt2": f}
for file, file_stats in compression_stats.items()
for pretok, (f, t) in file_stats.items()
]
Step 2: Create the Polars DataFrame
Next, we'll create a Polars DataFrame from the flattened data.
df = pl.DataFrame(flattened_data)
At this point, the DataFrame will look like this:
| file | pretok | bytes_gpt2 |
|---|
| file_1 | tok_1 | 100 |
| file_1 | tok_2 | 200 |
| file_2 | tok_1 | 150 |
| ... | ... | ... |
Step 3: Pivot the DataFrame
To reshape the DataFrame so that pretok becomes the columns and file becomes the index, we use the .pivot() method in Polars.
from_df = df.pivot(
index="file", # Rows will be indexed by `file`
columns="pretok", # Columns will be based on `pretok`
values="bytes_gpt2" # Cell values will be `bytes_gpt2`
)
Step 4: Sort the DataFrame (Optional)
If you want to sort the rows by a specific column (e.g., one of the pretok columns), you can do so after pivoting. For example:
from_df = from_df.sort("some_column", descending=True)
Final Output
The resulting from_df will have:
- Rows indexed by
file.
- Columns corresponding to unique
pretok values.
- Cell values representing the
bytes_gpt2 values.
For example:
| file | tok_1 | tok_2 | tok_3 |
|---|
| file_1 | 100 | 200 | null |
| file_2 | 150 | null | 300 |
| ... | ... | ... | ... |
Key Notes:
- Missing Values: If a
file does not have a value for a specific pretok, Polars will automatically fill the cell with null.
- Sorting: You can sort the DataFrame by any column after pivoting if needed.
Let me know if this matches your expectations or if you need further adjustments!