如何在该词典的Pandas数据框中引用键? [英] How can I reference the key in the Pandas dataframes within that dictionary?

查看:70
本文介绍了如何在该词典的Pandas数据框中引用键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本字典,在其中放置了几个数据框(此时全部相同).我正在尝试将数据添加到每个数据框(会计年度)的同一列中,该列与可以调用每个数据框的键相对应.我分配的关键字是会计年度.但是,当我尝试使用dict.items()时,它将为每个数据框分配相同的值(上一个会计年度).目的是按财政年度预测收入,在该收入中,我将根据每年获得的收入将收入划分为一个新列.我将代码简化如下:

I have a dictionary in which I've put several dataframes (all identical at this point). I'm trying to add data into the same column of each of those dataframes (fiscal year) corresponding to the key by which each dataframe can be called. The keys that I've assigned are the fiscal years. When I try to use dict.items(), however, it assigns each of the dataframes the same value (the last fiscal year). The goal is to forecast the revenue by fiscal year where I will break revenue into a new column according to how much will be garnered in each year. I've simplified my code to the below:

import pandas as pd
columns = ['ID','Revenue','Fiscal Year']
ID = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Revenue = [1000, 1200, 1300, 100 ,500, 0, 800, 950, 4321, 800]
FY = []
d = {'ID': ID, 'Revenue': Revenue}
df = pd.DataFrame(d)
df['Fiscal Year'] = ''
dataframe_dict = {}
def df_dict_func(start, end, dataframe):
    date_range = range(start, end + 1)
    for n in date_range:
        dataframe_dict[n] = dataframe
    for key, value in dataframe_dict.items():
        value['Fiscal Year'] = key
df_dict_func(2018, 2025, df)
print(dataframe_dict[2019])

推荐答案

似乎不必要在一个循环中创建dict键和值,然后在另一个循环中添加列名.相反,您的代码应该看起来像这样

Seems unnecessary to create the dict keys and values in one loop and then add a column name in another loop. Instead your code should look something like this

import pandas as pd

def df_dict_func(start, end, dataframe):
    date_range = range(start, end + 1)
    dataframe_dict = {}
    for n in date_range:
        sub = dataframe.copy()
        sub['Fiscal Year'] = n
        dataframe_dict[n] = sub
    return dataframe_dict


columns = ['ID','Revenue','Fiscal Year']
ID = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Revenue = [1000, 1200, 1300, 100 ,500, 0, 800, 950, 4321, 800]
FY = []
d = {'ID': ID, 'Revenue': Revenue}
df = pd.DataFrame(d)

df_dict = df_dict_func(2018, 2025, df)

print(df_dict[2019])

这篇关于如何在该词典的Pandas数据框中引用键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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