【问题标题】:Adding column to empty DataFrames via a loop通过循环将列添加到空 DataFrame
【发布时间】:2021-08-19 17:13:03
【问题描述】:

我有以下代码:

for key in temp_dict:
temp_dict[key][0][0] = temp_dict[key][0][0].insert(0, "Date", None)

temp_dict 在哪里:

    {'0.5SingFuel': [[Empty DataFrame
Columns: [Month, Trades, -0.25, -0.2, -0.15, -0.1, -0.05, 0.0, 0.05, 0.1, 0.15, 0.2, 0.25, Total]
Index: []]], 'Sing180': [[Empty DataFrame
Columns: [Month, Trades, -0.25, -0.2, -0.15, -0.1, -0.05, 0.0, 0.05, 0.1, 0.15, 0.2, 0.25, Total]
Index: []]], 'Sing380': [[Empty DataFrame
Columns: [Month, Trades, -0.25, -0.2, -0.15, -0.1, -0.05, 0.0, 0.05, 0.1, 0.15, 0.2, 0.25, Total]
Index: []]]}

我想要的是:

{'0.5SingFuel': [[Empty DataFrame
Columns: [Date, Month, Trades, -0.25, -0.2, -0.15, -0.1, -0.05, 0.0, 0.05, 0.1, 0.15, 0.2, 0.25, Total]
Index: []]], 'Sing180': [[Empty DataFrame
Columns: [Date, Month, Trades, -0.25, -0.2, -0.15, -0.1, -0.05, 0.0, 0.05, 0.1, 0.15, 0.2, 0.25, Total]
Index: []]], 'Sing380': [[Empty DataFrame
Columns: [Date, Month, Trades, -0.25, -0.2, -0.15, -0.1, -0.05, 0.0, 0.05, 0.1, 0.15, 0.2, 0.25, Total]
Index: []]]}

我的代码产生以下错误:

ValueError: cannot insert Date, already exists

我原以为我正在从一个 dict 键循环到下一个,但我正在通过调试器,它看起来像:

  • 代码做它应该做的事情
  • 移动到下一个键,前一个键变为空
  • 新键已经在列中有“日期”,然后代码尝试添加它,当然不能

这可能没有意义,因此我需要一些帮助 - 我很困惑。

我认为我错误地分配了变量,但不完全确定如何。

【问题讨论】:

    标签: python-3.x pandas dataframe dictionary


    【解决方案1】:

    一个问题是insert 是一种就地操作,因此您无需重新分配。第二个问题是如果该列存在,那么insert 不能像您所说的那样工作,因此您需要检查它是否已经在列中,并且可能重新排序以将此列放在首位。

    # dummy dictionary, same structure
    d = {0:[[pd.DataFrame(columns=['a','b'])]], 
         1:[[pd.DataFrame(columns=['a','c'])]]}
    
    # name of the column to insert
    col='c'
    
    for key in d.keys():
        df_ = d[key][0][0] # easier to define a variable
        if col not in df_.columns:
            df_.insert(0,col,None)
        else: # reorder and reassign in this case, remove the else if you don't need
            d[key][0][0] = df_[[col] + df_.columns.difference([col]).tolist()]
    print(d)
    # {0: [[Empty DataFrame
    # Columns: [c, a, b]                 # c added as column
    # Index: []]], 1: [[Empty DataFrame
    # Columns: [c, a]                    # c in first position now
    # Index: []]]}
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2013-05-25
    • 2021-05-19
    • 1970-01-01
    • 2016-08-25
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    相关资源
    最近更新 更多