gpt4 book ai didi

python - 在 DataFrame 中创建新列

转载 作者:行者123 更新时间:2023-11-28 17:15:22 24 4
gpt4 key购买 nike

我有一个包含几列的 DataFrame:

   'a'  'b'  'c'  'd'
0 'x' 3 3 5
1 'y' 2 3 6
2 'z' 1 4 1

我想创建一些依赖于数据的新列。对于“a”列中的每个可能值,我想要两个新列(我在“a”列中列出了所有不同的值。只有几个)。每列有两个条件:对于第一个新列,“a”列需要等于所需的值(例如“x”)并且“b”列等于“c”列。对于第二个新列,“a”列仍需要等于所需值,但“b”列需要等于“d”列(“b”列将等于“c”或“d”)。如果满足这两个条件,新列将获得 1,否则将获得 0。

下面是上面示例 DataFrame 的外观,假设:

一个。 “e”和“f”列的所需值为“x”

“g”和“h”列的所需值为“y”

“j”和“k”列的所需值为“z”

'e'、'g'、'h' 列是 'b' 和 'c' 列相等时

'f'、'h'、'k' 列是 'b' 和 'd' 列相等时

   'a'  'b'  'c'  'd'  'e'  'f'  'g'  'h'  'j'  'k'
0 'x' 3 3 5 1 0 0 0 0 0
1 'y' 2 3 6 0 0 0 0 0 0
2 'z' 1 4 1 0 0 0 0 0 1

我尝试对每个示例使用应用函数。这是当我们想要测试 'x' 并且列 'b' 和 'c' 相等时:

data['d']= data.apply(lambda row: assignEvent(row, 'x', row['c']), axis=1 )

此处使用 assignEvent 函数:

def assignEvent(row, event, venue):
"""
:param event: the desired event we're looking for
:param venue: Either column 'c' or 'd'
"""

if (str(row['a'])==event) & (str(venue)==str(row['b'])):
return 1
else:
return 0

它不起作用,因为当我完成时,新列中的所有值都是 0。我不确定为什么,因为我测试了它并且我知道我正在进入我的函数中的 if 语句。

最佳答案

我改变了一些东西。首先,您的 a 列数据有引号,所以我在 assignEvent 函数中用 replace 去除了那些。其次,我只将列名称作为参数传递给 venue,让我们在函数中访问该列。

def assignEvent(row, event, venue):
"""
:param event: the desired event we're looking for
:param venue: Either column 'c' or 'd'
"""

if (row['a'].replace("'","")==event) & (row[venue]==row['b']):
return 1
else:
return 0

df['dd']= df.apply(lambda row: assignEvent(row, 'x', 'c'), axis=1 )

输出:

     a  b  c  d  dd
0 'x' 3 3 5 1
1 'y' 2 3 6 0
2 'z' 1 4 1 0

关于python - 在 DataFrame 中创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44530686/

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