Code: Select all
import polars as pl
df = pl.DataFrame({
"Col Ind": ['A','B','C','D','E'],
"Col A": [1,2,3,4,5],
"Col B": [2,4,6,8,10],
"Col C": [1,3,5,7,9],
"Col D": [5,4,3,2,1] })
Um die beiden neuen Zeilen zu erstellen, musste ich mir die folgende sehr komplizierte Methode einfallen lassen:
Code: Select all
first_col = df.select("Col Ind").to_series().append(pl.Series("temp", ["Total", "Percentage"]))
df = df.drop("Col Ind")
cols = df.columns
expr = df.select(pl.sum(cols))
rowlist = list(expr.row(0))
full = sum(rowlist)
pc_row = []
for n in range(len(rowlist)):
pc_row.append(int(rowlist[n] /full *100))
pc_dict = dict(zip(cols, pc_row))
pc_df = pl.DataFrame(pc_dict)
df = pl.concat([df,expr])
df = pl.concat([df,pc_df])
df.insert_column(0, first_col)
Code: Select all
┌────────────┬───────┬───────┬───────┬───────┐
│ Col Ind ┆ Col A ┆ Col B ┆ Col C ┆ Col D │
│ --- ┆ --- ┆ --- ┆ --- ┆ --- │
│ str ┆ i64 ┆ i64 ┆ i64 ┆ i64 │
╞════════════╪═══════╪═══════╪═══════╪═══════╡
│ A ┆ 1 ┆ 2 ┆ 1 ┆ 5 │
│ B ┆ 2 ┆ 4 ┆ 3 ┆ 4 │
│ C ┆ 3 ┆ 6 ┆ 5 ┆ 3 │
│ D ┆ 4 ┆ 8 ┆ 7 ┆ 2 │
│ E ┆ 5 ┆ 10 ┆ 9 ┆ 1 │
│ Total ┆ 15 ┆ 30 ┆ 25 ┆ 15 │
│ Percentage ┆ 17 ┆ 35 ┆ 29 ┆ 17 │
└────────────┴───────┴───────┴───────┴───────┘
Gibt es einen einfacheren Weg?
Vielen Dank
Mobile version