所以我想在我的数据框架中创建一个新列,让我们称之为"结果"。我希望每个值都在"结果"根据其他两列中的值确定。所以,让我们说这是我的数据框:
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
答案 0 :(得分:2)
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
或者:
pyauto
答案 1 :(得分:0)
df_a.loc[(df_a['subject_id'] == 2) & (df_a['first_name'] == 'Amy'),'outcome']=2
df_a.loc[(df_a['subject_id'] > 0 ) & (df_a['first_name'] == 'Alice'),'outcome']=1
df_a['outcome'].fillna(0)
不如上述那么好,但看看你想做什么,这对你来说很重要。