开发者社区> 问答> 正文

操作后在循环中保存panda数据流

我有一个循环,它获取一系列现有的数据帧并操作它们的格式和值。我需要知道如何在循环结束时创建包含修改内容的新dataframes。 例子如下:

import pandas as pd

# Create datasets
First = {'GDP':[200,175,150,100]}
Second = {'GDP':[550,200,235,50]}

# Create old_dataframes
old_df_1 = pd.DataFrame(First)
old_df_2 = pd.DataFrame(Second)

# Define references and dictionary
old_dfs = [old_df_1, old_df_2]
new_dfs = ['new_df_1','new_df_2']
dictionary = {}

# Begin Loop
for df, name in zip(old_dfs, new_dfs):

    # Multiply all GDP values by 1.5 in both dataframes
    df = df * 1.5    

    # ISSUE HERE - Supposed to Create new data frames 'new_df_1' & 'new_df_2' containing df*1.5 values: Only appends to dictionary. Does not create new_df_1 & new_df_2
    dictionary[name] = df

# Check for the existance of 'new_df_1 & new_df_2' (They will not appear)
%who_ls DataFrame

问题:我已经在上面做了标记。我的代码没有创建'new_df_1' & 'new_df_2'数据流。它只是将它们附加到dictionary中。我需要能够创建new_df_1和new_df_2作为单独的数据流。 问题来源StackOverflow 地址:/questions/59384898/save-pandas-dataframes-in-loop-after-manipulating

展开
收起
kun坤 2019-12-26 10:52:12 402 0
1 条回答
写回答
取消 提交回答
  • 通过思考上面的答案,我最终找到了一个可行的解决方案。我面临的问题是——从字典中提取附加数据。我并没有真正想到我可以从循环外的字典中提取数据,然后形成数据框架。

    .
    .
    .
     # Begin Loop
        for df, name in zip(old_dfs, new_dfs):
        # Multiply all GDP values by 1.5 in both dataframes
        df = df * 1.5    
    
        # ISSUE HERE - Supposed to Create new data frames 'new_df_1' & 'new_df_2' containing df*1.5 values: Only appends to dictionary. Does not create new_df_1 & new_df_2
        dictionary[name] = df
    
    # Solution - Extract from Dictionary and form Dataframe
    new_df_1 = pd.DataFrame.from_dict(dictionary['new_df_1'])
    new_df_2 = pd.DataFrame.from_dict(dictionary['new_df_2'])
    
    # Check for the existance of 'new_df_1 & new_df_2'
    %who_ls DataFrame
    
    2019-12-26 10:52:19
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载