gpt4 book ai didi

python - 比较两个列值并根据比较再创建 2 个列

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

我有一个 pandas 数据框,我需要检查一个列值是否在另一个列值中可用,并根据它创建另外 2 列。

我的数据框看起来像这样:

Dept-x  Country Age Category    Dept-y
Math India Young Good Math,Social,English,Science,French
Math India Adult Good Math,Social,English,Science,French
Social Aus Young Average Science,Math,Social, English, French
Science Pak Young Good Math,Social,English,Practical,French
Science Pak Adult Average Math,Social,Science,French,English
Science Pak Adult Good Science,Math,Social, English, French

预期数据框:

Top 3   Top all
1 1
1 1
0 1
0 0
1 1
1 1

因此,在预期的数据框中,除了现有列之外,我们还需要添加两列(即 Top 3 和 Top all)。

如果 Dept-x 的值在 Dept-y 的前 3 个值中可用,则 Top 3 和 Top all 的值都应为 1。

如果 Dept-x 的值在前 3 个值中不可用,但在 Dept-y 中存在,则 Top 3 应为 0,Top all 应为 1。

如果 Dept-x 的值在 Dept-y 中根本不可用,则 Top 3 和 Top all 的值都应为 0。

如果有人可以帮助我实现这一目标,我将不胜感激?

最佳答案

您可以像这样使用列表理解:

df['Top 3']=[1 if x in y.split(',')[:3] else 0 for x,y in zip(df['Dept-x'], df['Dept-y'])]
df['Top all']=[1 if x in y else 0 for x,y in zip(df['Dept-x'], df['Dept-y'])]

关于python - 比较两个列值并根据比较再创建 2 个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54080499/

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