首页 > 解决方案 > 如何访问 Pandas 数据框的 Python 字典中的值、修改数据框并更新字典值

问题描述

对 Python 很陌生,尤其是字典,找不到任何关于我想要做什么的具体内容。

本质上,我有一个 Pandas 数据框的 OrderedDict(我读入并转换为数据框的一堆 Excel 表),我想单独访问这些数据框,修改它们,然后在 OrderedDict 中更新它们,但不太确定如何这样做。

如前所述,我对此很陌生,所以我知道如何更新数据框,但不知道如何将其存储回字典中。目前,我的代码如下所示:

for sheet in cons_excel_sheets:
    df = cons_excel_sheets[sheet]
    row = df[df['Row Labels'] == 'Grand Total'].index.tolist()[0]
    df = df.iloc[:row - 1]
    cleaned_dataframes_list.update(df)

这将返回以下错误(如果我一次只更新一个数据帧,即没有 for 循环,则此方法有效):

    Traceback (most recent call last):
  File "C:\Users\USER\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-38dbbba27fa0>", line 5, in <module>
    row = df[df['Row Labels'] == 'Grand Total'].index.tolist()[0]
IndexError: list index out of range

不知道如何解决这个错误,也怀疑我在 for 循环结束时正确更新了 OrderedDict。

有任何想法吗?

标签: pythonpandasdictionary

解决方案


您可以使用一些示例数据进行尝试:

#DataFrames generated from the excel files
value_df1 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns= 
            ['a', 'b', 'c'])
value_df2 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns= 
            ['a', 'b', 'c'])
value_df3 = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), columns= 
            ['a', 'b', 'c'])                   

#Making a Dictionary of the Dataframes
dict = {
  "key0": value_df1,
  "key1": value_df2,
  "key2": value_df3
}

#Accessing an element in a particular DataFrame (e.g. value_df2 - column b)
tempDataFrame = dict[key1]
tempDataFrame = tempDataFrame['b']

#Iterate through dictionary and update value(s) in a DataFrame(e.g. value_df3 - setting column a values to 0)
for k,val in  dict:
    tempDataFrame = dict[k]
    tempDataframe['a'] = 0
    dict[k] = tempDataFrame

我希望这回答了你的问题。


推荐阅读