首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >python-polars使用字典按列值将数据分解为多个dfs。

python-polars使用字典按列值将数据分解为多个dfs。
EN

Stack Overflow用户
提问于 2022-09-20 11:20:09
回答 1查看 175关注 0票数 1

我希望使用字典将单个df拆分为多个dfs,使用唯一的列值。下面的代码显示了如何使用熊猫来完成这个任务。我怎样才能在极地做下面的事情呢?

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-20 12:04:29

Polars有一个DataFrame方法来处理这个问题:partition_by。使用as_dict关键字创建DataFrames字典。

代码语言:javascript
复制
df.partition_by(groups="Favorite_Color", as_dict=True)
代码语言:javascript
复制
{'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          │
└────────────────┘}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73785866

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档