【问题标题】:dicionary filled with dataframes restructuring充满数据框重组的字典
【发布时间】:2020-06-02 09:42:51
【问题描述】:

我正在尝试重新构建一个包含多个数据帧的字典。我找到了一个解决方案,但由于我是 Python 新手,所以它是一个相当原始的解决方案。因为当我增加字典中数据帧的数量时我的解决方案非常慢,所以我想问是否有人知道如何改进我现有的代码或知道替代解决方案:

我有一本由三个 df 组成的字典,其中包含有关国家/地区的信息。举个例子:

# example dictionary filled with dataframes
import pandas as pd
import numpy as np

dic_old={}

countries = ['USA', 'China', 'India']
col = ['factor 1','factor 2','factor 3']
ind = pd.DatetimeIndex(start ='2019-01-10', freq ='m',  periods = 5) 

df1=pd.DataFrame(np.random.rand(5,3),columns=col, index = ind)    
df2=pd.DataFrame(np.random.rand(5,3),columns=col, index = ind)
df3=pd.DataFrame(np.random.rand(5,3),columns=col, index = ind)

dic_old['USA']=df1
dic_old['China']=df2
dic_old['India']=df3

现在我想重组这本词典。我现在不想拥有包含每个单独国家/地区信息的 3 个数据框,而是希望每个日期都有一个包含所有国家/地区信息的数据框。因此,我的字典将从 3 个 5 行 à 3 列的数据帧变为一个具有 5 个数据帧和 3 行 3 列的新字典。我设法用以下代码做到了这一点:

dates = ind.tolist()
factors = dic_old['USA'].columns
dic_new = {}

# Create empty dataframes with desired column headers and index
for d in dates:
    dic_new[d.strftime('%Y-%m')] = pd.DataFrame(index=countries, columns = factors) #

# fill empty dataframes with info from dic_old
for y in dates:
    for e in countries:
        dic_new[y.strftime('%Y-%m')].loc[e] = dic_old[e].loc[y]

现在,如果我增加数据框的数量(假设我添加了更多国家和更多日期),那么我的代码会变得非常慢。考虑到我使用 3 个 for 循环,这可能并不奇怪,因为循环速度很慢。有谁知道我可以如何让我的代码运行得更快,或者有没有人看到解决我的问题的替代方法?

提前感谢,任何帮助表示赞赏

【问题讨论】:

    标签: python dataframe dictionary


    【解决方案1】:

    我认为您应该更改程序的设计。 为什么不只有一个 DataFrame 呢?

    看看 append 方法 (docs) 或 concat 方法 (docs)。

    如果您想快速复制数据,请使用合并方法 (docs) 和两个数据帧(即日期和因子),并使用一个虚拟键(即 df["key"]=0)来执行笛卡尔积。

    【讨论】:

    • 感谢您的评论。我知道 append 和 concat 方法,但是因为我有多个因素结合多个国家和时间序列,所以我需要为我的数据有一个 3D 结构。 (X轴因素,Y轴时间和Z轴不同国家)
    • 那么您应该相应地更新您的问题,使用更具体的标题以及添加一些像这样的约束。我仍然会使用以前的解决方案,例如,当您想使用 Z 轴的某个值访问 X 轴时,按国家/地区访问它。 df[df["country"]=="USA"][factors]
    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 2013-11-08
    • 2022-01-21
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    相关资源
    最近更新 更多