Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List to DataFrame with row and column headers

I need to convert a list (including headers) to a Dataframe.

If I do it directly using pl.DataFrame(list), the headers are created and everything is kept as a string. Moreover, the table is transposed, such that the first element in the list becomes the first column in the dataframe.

Input list.

[
    ['Earnings estimate', 'Current qtr. (Jun 2024)', 'Next qtr. (Sep 2024)', 'Current year (2024)', 'Next year (2025)'],
    ['No. of analysts', '13', '11', '26', '26'],
    ['Avg. Estimate', '1.52', '1.62', '6.27', '7.23'],
    ['Low estimate', '1.36', '1.3', '5.02', '5.88'],
    ['High estimate', '1.61', '1.74', '6.66', '8.56'],
    ['Year ago EPS', '1.76', '1.36', '5.74', '6.27'],
]

Expected output.

Expected Output

like image 478
Rhys Avatar asked Oct 28 '25 02:10

Rhys


1 Answers

You can explicitly define the orient= to prevent transposition:

pl.DataFrame(data[1:], orient="row", schema=data[0])
shape: (5, 5)
┌───────────────────┬─────────────────────────┬──────────────────────┬─────────────────────┬──────────────────┐
│ Earnings estimate ┆ Current qtr. (Jun 2024) ┆ Next qtr. (Sep 2024) ┆ Current year (2024) ┆ Next year (2025) │
│ ---               ┆ ---                     ┆ ---                  ┆ ---                 ┆ ---              │
│ str               ┆ str                     ┆ str                  ┆ str                 ┆ str              │
╞═══════════════════╪═════════════════════════╪══════════════════════╪═════════════════════╪══════════════════╡
│ No. of analysts   ┆ 13                      ┆ 11                   ┆ 26                  ┆ 26               │
│ Avg. Estimate     ┆ 1.52                    ┆ 1.62                 ┆ 6.27                ┆ 7.23             │
│ Low estimate      ┆ 1.36                    ┆ 1.3                  ┆ 5.02                ┆ 5.88             │
│ High estimate     ┆ 1.61                    ┆ 1.74                 ┆ 6.66                ┆ 8.56             │
│ Year ago EPS      ┆ 1.76                    ┆ 1.36                 ┆ 5.74                ┆ 6.27             │
└───────────────────┴─────────────────────────┴──────────────────────┴─────────────────────┴──────────────────┘
like image 153
jqurious Avatar answered Oct 30 '25 19:10

jqurious



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!