python pandas-使用for循环编辑多个DataFrame [英] python pandas - Editing multiple DataFrames with a for loop

查看:1753
本文介绍了python pandas-使用for循环编辑多个DataFrame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下2个列表,其中包括3个字典和3个空的DataFrames

Considering the following 2 lists of 3 dicts and 3 empty DataFrames

dict0={'actual': {'2013-02-20 13:30:00': 0.93}}
dict1={'actual': {'2013-02-20 13:30:00': 0.85}}
dict2={'actual': {'2013-02-20 13:30:00': 0.98}}
dicts=[dict0, dict1, dict2]

df0=pd.DataFrame()
df1=pd.DataFrame()
df2=pd.DataFrame()
dfs=[df0, df1, df2]

我想通过使用以下行来递归地修改循环中的3个数据框:

I want to recursively modify the 3 Dataframes within a loop, by using the following line:

for df, dikt in zip(dfs, dicts):
    df = df.from_dict(dikt, orient='columns', dtype=None)

但是,当尝试在循环外检索df的实例1时,它仍然为空

However, when trying to retrieve for instance 1 of the df outside of the loop, it is still empty

print (df0)

将返回

Empty DataFrame
Columns: []
Index: []

从for循环中打印df时,虽然可以看到数据已正确附加.

When printing the df from within the for loop, we can see the data is correctly appended though.

如何制作循环,以便可以在循环外打印3个df及其更改?

How to make the loop so that it is possible to print the 3 dfs with their changes outside of the loop?

推荐答案

在您的循环中,df只是一个临时值,而不是对相应列表元素的引用.如果要在迭代时修改列表,则必须按索引引用列表.您可以使用Python的枚举来做到这一点:

In your loop, df is just a temporary value, not a reference to the corresponding list element. If you want to modify the list while iterating it, you have to reference the list by index. You can do that using Python's enumerate:

for i, (df, dikt) in enumerate(zip(dfs, dicts)):
    dfs[i] = df.from_dict(dikt, orient='columns', dtype=None)

这篇关于python pandas-使用for循环编辑多个DataFrame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆