gpt4 book ai didi

python - 使用 2 列匹配多列的值

转载 作者:行者123 更新时间:2023-12-01 08:12:46 25 4
gpt4 key购买 nike

示例 DF:

ID   Name     Match1    Random_Col    Match2    Price    Match3     Match4       Match5
1 Apple Yes Random Value No 10 Yes Yes Yes
2 Apple Yes Random Value1 No 10 Yes Yes No
3 Apple Yes Random Value2 No 15 No Yes Yes
4 Orange No Random Value Yes 12 Yes Yes No
5 Orange No Random Value Yes 12 No No No
6 Banana Yes Random Value No 15 Yes No No
7 Apple Yes Random Value No 15 No Yes Yes

预期 DF:

ID   Name     Match1    Random_Col    Match2  Price Match3  Match4 Match5 Final_Match
1 Apple Yes Random Value No 10 Yes Yes Yes Full
2 Apple Yes Random Value1 No 10 Yes Yes No Partial
3 Apple Yes Random Value2 No 15 No Yes Yes Partial
4 Orange No Random Value Yes 12 Yes Yes No Full
5 Orange No Random Value Yes 12 No No No Partial
6 Banana Yes Random Value No 15 Yes No No Full
7 Apple Yes Random Value No 15 No Yes Yes Partial

问题陈述:

  1. 如果组合 NamePrice 不重复,只需将 Full 放入 Final_Match 列(示例 ID 6 )
  2. 如果组合NamePrice重复,则在其中计数Match1到Match5列中的Yes,以具有较大值的"is",为其中一个输入 Full,为另一个输入 Partial(示例 ID 1、2 和 4,5)

  3. 如果组合 NamePrice 重复,则在 Match1 到 Match5 列的 ID 计数内 Yes(如果它们有)等于"is",将 Partial 放入两者中(示例 ID 3,7)

代码

s = (df.replace({'Yes': 1, 'No': 0})
.iloc[:, 1:]
.sum(1))

df['final_match'] = np.where(s.groupby(df[['Price','Name']]).rank(ascending=False).eq(1), 'Full ','Partial')

当我必须groupby仅按1列时,上面的代码可以工作,比如Name,但它不适用于组合。

任何帮助!!

最佳答案

用途:

#count Yes values only in Match columns
s = df.filter(like='Match').eq('Yes').sum(axis=1)
#mask for unique combinations
m1 = ~df.duplicated(['Price','Name'], keep=False)
#create new column filled by Series s
m2 = df.assign(new=s).groupby(['Price','Name'])['new'].rank(ascending=False).eq(1)
#chain masks by bitwise OR
df['final_match'] = np.where(m1 | m2, 'Full ','Partial')
print (df)

ID Name Match1 Random_Col Match2 Price Match3 Match4 Match5 \
0 1 Apple Yes Random Value No 10 Yes Yes Yes
1 2 Apple Yes Random Value1 No 10 Yes Yes No
2 3 Apple Yes Random Value2 No 15 No Yes Yes
3 4 Orange No Random Value Yes 12 Yes Yes No
4 5 Orange No Random Value Yes 12 No No No
5 6 Banana Yes Random Value No 15 Yes No No
6 7 Apple Yes Random Value No 15 No Yes Yes

final_match
0 Full
1 Partial
2 Partial
3 Full
4 Partial
5 Full
6 Partial

关于python - 使用 2 列匹配多列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55137758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com