gpt4 book ai didi

Python——添加考虑其他列值的新列来为新列创建值

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

所以我想在我的数据框中创建一个新列,我们称之为“结果”。我希望“结果”中的每个值根据其他两列中的值来确定。假设这是我的数据框:

raw_data = {
'subject_id': ['1', '2', '3', '4', '5'],
'first_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],
'last_name': ['Anderson', 'Ackerman', 'Ali', 'Aoni', 'Atiches']}
df_a = pd.DataFrame(raw_data, columns = ['subject_id', 'first_name', 'last_name'])

这就是数据框的样子:

  subject_id first_name last_name
0 1 Alex Anderson
1 2 Amy Ackerman
2 3 Allen Ali
3 4 Alice Aoni
4 5 Ayoung Atiches

所以我想创建一个新的列,其逻辑如下:

if(df_a[df_a['subject_id'] == 2] & df_a[df_a['first_name'] == 'Amy']):
df_a['outcome'] = 2
elif(df_a[df_a['subject_id'] > 0] & df_a[df_a['first_name'] == 'Alice']):
df_a['outcome'] = 1
else:
df_a['outcome'] = 0

但我似乎无法让它正常工作。我希望新专栏看起来像这样:

  subject_id first_name last_name outcome
0 1 Alex Anderson 0
1 2 Amy Ackerman 2
2 3 Allen Ali 0
3 4 Alice Aoni 1
4 5 Ayoung Atiches 0

最佳答案

使用numpy.selectnumpy.where :

#first convert `subject_id` to int
df_a['subject_id'] = df_a['subject_id'].astype(int)
m1 = (df_a['subject_id'] == 2) & (df_a['first_name'] == 'Amy')
m2 = (df_a['subject_id'] > 0) & (df_a['first_name'] == 'Alice')

df_a['outcome'] = np.select([m1, m2], [2,1], default=0)
print (df_a)
subject_id first_name last_name outcome
0 1 Alex Anderson 0
1 2 Amy Ackerman 2
2 3 Allen Ali 0
3 4 Alice Aoni 1
4 5 Ayoung Atiches 0

或者:

df_a['outcome'] = np.where(m1, 2, np.where(m2, 1, 0))
print (df_a)
subject_id first_name last_name outcome
0 1 Alex Anderson 0
1 2 Amy Ackerman 2
2 3 Allen Ali 0
3 4 Alice Aoni 1
4 5 Ayoung Atiches 0

关于Python——添加考虑其他列值的新列来为新列创建值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46503518/

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