熊猫,了解数据框的行为

时间:2020-04-30 07:11:09

标签: python pandas list dictionary

我有一个熊猫数据框,我正在从中提取一些数据框。

我正在将每个数据帧分配为字典中的一个值。

class AssignBags:
    df = pd.read_csv(f'{PATH}{RESOURCES}{UPDATED_ITEMS_FILE}')
    team = None
    bags_list = None
    if bags_list is None:
        bags_list = []

    @classmethod
    def assign_bags_to_people(cls, lens):

        for bag_len in lens:
            bags = {
                bag_len: cls.df.groupby([DfConsts.ASSIGNED_BAG]).get_group(bag_len)[
                    [DfConsts.ITEM, DfConsts.WEIGHT]]
            }
            cls.bags_list.append(bags)
            return cls.bags_list

我正在努力理解的行为如下:

# if I print cls.bags_dict 


    def assign_bags_to_people(cls, lens):
        try:
            for bag_len in lens:
                cls.bags_dict = {
                    bag_len: cls.df.groupby([DfConsts.ASSIGNED_BAG]).get_group(bag_len)[
                        [DfConsts.ITEM, DfConsts.WEIGHT]]
                }
                print(cls.bags_dict)

输出符合我的预期

{'planes bag':                Item  Weight
0        planes bag    8.50
1   Full Bandolera     3.76
2   Full Bandolera     3.76
3   Full Bandolera     3.76
28           hammer    1.28
29           Baznat    0.72
30           Bungee    1.26}
{'pods bag':         Item  Weight
19  pods bag    8.72
20       Pod    1.74
21       Pod    1.74
22       Pod    1.74
23     optic    0.86
24     optic    0.86
25   thermal    1.20
26   thermal    1.20
27   thermal    1.20}
{'ground system bag':                  Item  Weight
35  Ground System Bag    8.00
36             Tablet    9.65}

但是如果我将return作为第一个代码,然后尝试在其他地方使用它:

@classmethod
    def assign_bags_to_people(cls, lens):
        try:
            for bag_len in lens:
                bags = {
                    bag_len: cls.df.groupby([DfConsts.ASSIGNED_BAG]).get_group(bag_len)[
                        [DfConsts.ITEM, DfConsts.WEIGHT]]
                }
                cls.bags_list.append(bags)
                return cls.bags_list

        except:
            if KeyError:
                """
                Low Bag hasn't been assigned yet.
                """
            pass

    @classmethod
    def print_bags_dict(cls):
        pprint(cls.bags_list)

它仅打印第一项:

[{'planes bag':                Item  Weight
0        planes bag    8.50
1   Full Bandolera     3.76
2   Full Bandolera     3.76
3   Full Bandolera     3.76
28           hammer    1.28
29           Baznat    0.72
30           Bungee    1.26}]

0 个答案:

没有答案