我希望使用字典将单个df拆分为多个dfs,使用唯一的列值。下面的代码显示了如何使用熊猫来完成这个任务。我怎样才能在极地做下面的事情呢?
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)发布于 2022-09-20 12:04:29
Polars有一个DataFrame方法来处理这个问题:partition_by。使用as_dict关键字创建DataFrames字典。
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 │
└────────────────┘}https://stackoverflow.com/questions/73785866
复制相似问题