【问题标题】:subset dataframe in to multiple using a dictionary使用字典将数据帧子集到多个
【发布时间】:2021-11-19 16:44:24
【问题描述】:

我需要根据存储在字典中的列名的 start 将一个数据帧分成三个子集。

这是一个df:

df = pd.DataFrame(np.random.randint(0,5,size=(5, 10)), columns=('a_group1_sub','a_group1_actual','b_group1_sub','b_group1_actual','b_group2_total','b_group2_sub','b_group2_expected','class_first','class_second','area_x'))

这是一个字典,我想根据以下分组来分隔数据框:df1 = a_group1, df2 b_group2 and b_group2, df3 = class and area

groups = dict({1: ['a_group1'], 2: ['b_group1', 'b_group2'], 3: ['class', 'area']})

这是我尝试过的循环

for k, v in groupings.items():
    print(df.loc[:,df.columns.str.startswith([v])])

如果我做这样的事情,它会起作用,但不是在循环中

df.loc[:,df.columns.str.startswith('a_group1')])

欢迎任何cmets,非常感谢

【问题讨论】:

    标签: python pandas dataframe dictionary subset


    【解决方案1】:

    这就是你想要做的吗?

    df_list = list() # The output list of dataframes
    for k, v in groups.items(): # for v in groups.values() if you don't use k
        # Get the columns that start with any of the elements in v
        cols = [c for c in df.columns if c.startswith(tuple(v))]
        # Subset df, df[cols], and append to the list of dataframes
        df_list.append(df[cols])
    
    # df_list[i] contains the dataframe i
    

    【讨论】:

    • 谢谢!这几乎是我想要的......但它没有将输出保存到新的数据帧。理想情况下,我想将新数据帧存储在三个字典中,以便可以通过例如访问它们。 df[0], df[1], df[2] 我刚刚添加了 x = df[cols] / out.append([x])
    • 存储每个结果数据帧的方式和位置取决于您。我编辑了答案并添加了一个选项。理论上你也可以使用字典。
    猜你喜欢
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 2018-12-15
    • 2020-09-13
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    相关资源
    最近更新 更多