df1:
ID
0 9712
1 9920
2 9712
3 9560
4 9560
df2:
ID Absent Comp-off
0 9712 12/15/2021
1 9920 4/11/2021
2 9712 08/30/2021
3 9560 07/3/2021
4 9560
In df1, I need to create a column 'Status'. For an ID if any data is present in 'Absent' or 'comp-off' columns of df2 Status is 'A' else 'P'. How can I achieve it using if else condition?
CodePudding user response:
Use this code, it is not an optimized one, but it can do that job.
I recreated your dataframe
s like this below,
import pandas as pd
df1 = pd.DataFrame({'ID':['9712','9920','9712','9560','9560']})
df2 = pd.DataFrame({'ID':['9712','9920','9712','9560','9560'],
'Absent':['12/15/2021','','','07/3/2021',''],
'Comp-off':['','4/11/2021','08/30/2021','','']})
and here is the solutions,
status =[]
for i,j in df2.iterrows():
if j['Absent'] != '':
status.append('A')
elif j['Comp-off'] != '':
status.append('P')
else:
status.append('')
df1['Status'] = status
Sample output:
ID Status
0 9712 A
1 9920 P
2 9712 P
3 9560 A
4 9560
CodePudding user response:
Try using this code:
b1=pd.isnull(df2['Absent'])
b2=pd.isnull(df2['Compoff'])
df['Status'] =['P' if b else 'A' for b in np.array(b1&b2)]
And this is the sample output I got.
df
ID Status
0 9712 A
1 9920 A
2 9712 A
3 9560 A
4 9560 P
I hope this is what you are looking for.
Thank you.