You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Pandas通过循环将Dataframe拆分为独立Dataframe

解决方案:自动拆分Dataframe为按name命名的独立Dataframe

没问题,这个需求用pandas的groupby配合循环就能轻松实现,这里给你两种常用的方案,按需选择:

方法1:直接生成全局命名的Dataframe(如df_joe、df_mary)

这种方法会直接在全局环境中创建以df_{name}命名的独立Dataframe,适合分组数量不多、想直接通过变量名调用的场景。

完整代码示例

import pandas as pd

# 构造示例数据
data = {
    'name': ['joe', 'mary', 'pete', 'mary', 'pete', 'joe'],
    'color': ['yellow', 'green', 'blue', 'red', 'blue', 'orange'],
    'value': [7.0, 9.0, 8.0, 8.8, 7.7, 2.0]
}
df = pd.DataFrame(data)

# 自动拆分并生成全局变量
for name, group in df.groupby('name'):
    # 用f-string拼接变量名,通过globals()创建全局变量
    globals()[f'df_{name}'] = group

# 验证结果
print("df_joe的内容:")
print(df_joe)
print("\ndf_mary的内容:")
print(df_mary)

运行后你就能直接通过df_joe、df_mary、df_pete这些变量访问对应的数据了。

方法2:用字典统一存储分组后的Dataframe(更推荐)

如果你的分组数量较多,或者想更规范地管理这些拆分后的Dataframe,用字典存储是更好的选择——它不会污染全局变量空间,还能方便地遍历所有分组。

完整代码示例

import pandas as pd

# 构造示例数据
data = {
    'name': ['joe', 'mary', 'pete', 'mary', 'pete', 'joe'],
    'color': ['yellow', 'green', 'blue', 'red', 'blue', 'orange'],
    'value': [7.0, 9.0, 8.0, 8.8, 7.7, 2.0]
}
df = pd.DataFrame(data)

# 创建字典存储所有分组后的Dataframe
grouped_dfs = {}
for name, group in df.groupby('name'):
    grouped_dfs[name] = group

# 访问指定分组的Dataframe
print("joe的数据:")
print(grouped_dfs['joe'])
print("\nmary的数据:")
print(grouped_dfs['mary'])

# 遍历所有分组
print("\n所有分组数据:")
for name, group_df in grouped_dfs.items():
    print(f"\n--- {name} 的数据 ---")
    print(group_df)

两种方法的核心逻辑

不管用哪种方法,核心都是df.groupby('name')——它会自动把原Dataframe按name列的值分成多个组,每个组对应一个同名的子Dataframe。然后通过循环遍历这些组,把每个组的Dataframe赋值给对应的变量或字典键即可。

内容的提问来源于stack exchange,提问作者Windstorm1981

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:26:56