我有以下脚本:
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语句?你知道吗
为了使条件更具动态性,可以如下重构函数:
然后就可以像以前一样调用函数,但要包含主组列的序列
相关问题 更多 >
编程相关推荐