Python-Polars: Zeilen auswählen und als Überschriften mit Trennzeichen verwendenPython

Python-Programme
Anonymous
 Python-Polars: Zeilen auswählen und als Überschriften mit Trennzeichen verwenden

Post by Anonymous »

Beschreibung
Da Polars nicht wie Pandas mit Multi-Index-Headern funktioniert, würde ich gerne wissen, ob es eine native Möglichkeit gibt, Folgendes zu tun:
Meine aktuelle Implementierung muss zuerst Pandas durchlaufen und es dann in einen pl.DataFrame konvertieren.

# ----- Multiindex DataFrame -----

arrays = [["A", "A", "B", "B"], ["one", "two", "one", "two"]]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples)
pandas_multiindex_df = pd.DataFrame([[1, 2, 3, 4], [5, 6, 7, 8]], columns=index)
print(pandas_multiindex_df)

A B
one two one two
0 1 2 3 4
1 5 6 7 8

Note: This simulates an input excel that is separated by headers, so I will always have the data like this

Ihre Arbeitsweise ist:
  • Flat the pandas_df
def multiindex_to_flatted_header(df: pd.DataFrame, sep: str = "-") -> pd.DataFrame:
flat_columns = [f"{col[0]}{sep}{col[1]}" for col in df.columns]

df_flat = df.copy()
df_flat.columns = flat_columns

return df_flat

pandas_flatted_df = multiindex_to_flatted_header(pandas_multiindex_df)
print(pandas_flatted_df)

A-one A-two B-one B-two
0 1 2 3 4
1 5 6 7 8
  • Zu den Polaren wechseln
polars_flatted_df = pl.from_pandas(pandas_flatted_df)
print(polars_flatted_df)

shape: (2, 4)
┌───────┬───────┬───────┬───────┐
│ A-one ┆ A-two ┆ B-one ┆ B-two │
│ --- ┆ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 ┆ i64 │
╞═══════╪═══════╪═══════╪═══════╡
│ 1 ┆ 2 ┆ 3 ┆ 4 │
│ 5 ┆ 6 ┆ 7 ┆ 8 │
└───────┴───────┴───────┴───────┘

# Do stuff with polars performing operations
  • Zurück zu Pandas
pandas_flatted_df_2 =polars_flatted_df.to_pandas()

def flatted_to_multiindex_header(df: pd.DataFrame, sep: str = "-") -> pd.DataFrame:
df.columns = pd.MultiIndex.from_tuples(
[col.split(sep, 1) if sep in col else [col, ""] for col in df.columns]
)
return df

pandas_multiindex_df_2 = flatted_to_multiindex_header(pandas_flatted_df_2)
print(pandas_multiindex_df_2)

A B
one two one two
0 1 2 3 4
1 5 6 7 8

Note: I'm going back to pandas only because I need the resulting excel to have a presentation, but this step is not necessary

Die Frage ist:
Gibt es eine Möglichkeit, dasselbe mit Polaren zu tun (eine Excel-Datei/einen Pandas_Multiindex zu reduzieren)? Zum Beispiel use_rows_and_join_with_any_separator_and_use_as_header.
Ich denke, dass es zu Leistungsproblemen führen könnte, wenn ich dies auf meine Weise mache, wenn die Verwendung großer Datensätze mit einer Polars-Implementierung verbessert wird.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post