依赖于循环的IF语句

2024-07-05 10:28:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下脚本:

import pandas as pd

ls = [
      ['A', 1, 'A1', 9],
      ['A', 1, 'A1', 6],
      ['A', 1, 'A1', 3],
      ['A', 2, 'A2', 7],
      ['A', 3, 'A3', 9],
      ['B', 1, 'B1', 7],
      ['B', 1, 'B1', 3],
      ['B', 2, 'B2', 7],
      ['B', 2, 'B2', 8],
      ['C', 1, 'C1', 9],

      ]

#convert to dataframe
df = pd.DataFrame(ls, columns = ["Main_Group", "Sub_Group", "Concat_GRP_Name", "X_1"]) 

#get count and sum of concatenated groups
df_sum = df.groupby('Concat_GRP_Name')['X_1'].agg(['sum','count']).reset_index()

#print in permutations formula to calculate different permutation combos   
import itertools as it
perms = it.permutations(df_sum.Concat_GRP_Name)


def combute_combinations(df, colname):
    l = []
    import itertools as it
    perms = it.permutations(df[colname])

    for perm_pairs in perms:
        #take in only the first three pairs of permuations and make sure
        #the first column starts with A, secon with B, and third with C
        if 'A' in perm_pairs[0] and 'B' in perm_pairs[1] and 'C' in perm_pairs[2]:
            l.append([perm_pairs[0], perm_pairs[1], perm_pairs[2]])
    return l

#apply function, this will generate a list of all of the permuation pairs
t = combute_combinations(df_sum, 'Concat_GRP_Name' )

#convert to dataframe and drop duplicate pairs
df2 = pd.DataFrame(t, columns = ["Item1", 'Item2', 'Item3']) .drop_duplicates()

我不知道如何在IF语句中组合循环的组件。 从上面的例子中,我知道我有三种不同类型的主组变量。假设我不知道主组列中存在多少唯一值。如何更新下面的IF语句来解释这个问题?你知道吗

if 'A' in perm_pairs[0] and 'B' in perm_pairs[1] and 'C' in perm_pairs[2]:
                l.append([perm_pairs[0], perm_pairs[1], perm_pairs[2]])

我希望每个变量都在它自己的列中。如果我有5种类型的主组,那么在If语句中会有perm\u对[0]到perm\u对[4]。我在考虑提取主组中的值并将其转换为一个集合。然后我会遍历每个值,并使用它的长度来计算IF语句,但到目前为止,逻辑还没有实现。如何遍历集合,然后更新IF语句?你知道吗


Tags: andofnameinimportdfifit
1条回答
网友
1楼 · 发布于 2024-07-05 10:28:16

为了使条件更具动态性,可以如下重构函数:

import numpy as np

def combute_combinations(df, colname, main_group_series):
    l = []
    import itertools as it
    perms = it.permutations(df[colname])

    # Provides sorted list of unique values in the Series
    unique_groups = np.unique(main_group_series)

    for perm_pairs in perms:
        #take in only the first three pairs of permuations and make sure
        #the first column starts with A, secon with B, and third with C
        if all([main_group in perm_pairs[ind] for ind, main_group in enumerate(unique_groups)]):
            l.append([perm_pairs[ind] for ind in range(unique_groups.shape[0])])
    return l

然后就可以像以前一样调用函数,但要包含主组列的序列

t = combute_combinations(df_sum, 'Concat_GRP_Name', df['Main_Group'])

相关问题 更多 >