【问题标题】:python-polars split dataframe into many dfs by column value using dictionarypython-polars 使用字典按列值将数据帧拆分为多个 df
【发布时间】:2023-02-16 04:31:08
【问题描述】:
我想使用字典按唯一列值将单个 df 拆分为多个 df。下面的代码显示了如何使用 pandas 完成此操作。我如何在 polars 中执行以下操作?
import pandas as pd
#Favorite color of 10 people
df = pd.DataFrame({"Favorite_Color":["Blue","Yellow","Black","Red","Blue","Blue","Green","Red","Red","Blue"]})
print(df)
#split df into many dfs by Favorite_Color using dict
dict_of_dfs={key: df.loc[value] for key, value in df.groupby(["Favorite_Color"]).groups.items()}
print(dict_of_dfs)
【问题讨论】:
标签:
python
pandas
python-polars
【解决方案1】:
Polars 为此提供了一个 DataFrame 方法:partition_by。使用 as_dict 关键字创建 DataFrame 字典。
df.partition_by(groups="Favorite_Color", as_dict=True)
{'Blue': shape: (4, 1)
┌────────────────┐
│ Favorite_Color │
│ --- │
│ str │
╞════════════════╡
│ Blue │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ Blue │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ Blue │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ Blue │
└────────────────┘,
'Yellow': shape: (1, 1)
┌────────────────┐
│ Favorite_Color │
│ --- │
│ str │
╞════════════════╡
│ Yellow │
└────────────────┘,
'Black': shape: (1, 1)
┌────────────────┐
│ Favorite_Color │
│ --- │
│ str │
╞════════════════╡
│ Black │
└────────────────┘,
'Red': shape: (3, 1)
┌────────────────┐
│ Favorite_Color │
│ --- │
│ str │
╞════════════════╡
│ Red │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ Red │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ Red │
└────────────────┘,
'Green': shape: (1, 1)
┌────────────────┐
│ Favorite_Color │
│ --- │
│ str │
╞════════════════╡
│ Green │
└────────────────┘}