Поскольку Polars не работает с многоиндексными заголовками, как Pandas, я хотел бы знать, существует ли собственный способ сделать следующее:
Моя текущая реализация должна сначала пройти через Pandas, а затем преобразовать ее в pl.DataFrame.
Код: Выделить всё
# ----- 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
- Сглаживание 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
- перейти к полярам
Код: Выделить всё
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
- Вернуться к пандам
Код: Выделить всё
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
есть ли способ сделать то же самое (сгладить excel_file/pandas_multiindex) с полярами? например, use_rows_and_join_with_any_separator_and_use_as_header.
Я думаю, что выполнение этого на моем пути может вызвать проблемы с производительностью при использовании больших наборов данных с реализацией поляров.
Подробнее здесь: https://stackoverflow.com/questions/793 ... -separator