python pandas for循环_python pandas-使用for循环编辑多个DataFrame

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]

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)

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

print (df0)

will return

Empty DataFrame

Columns: []

Index: []

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

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

解决方案

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值