'If Elif statement isn't working properly >> only reads first elif and jumps the other ones after it - python
So I created this function to apply to a bunch of dataframes that I have inside a dictionary. The thing is, when it comes to the elif part he only does the first statement that he reads.
So for example if I don't have the column 'claimant moderated resultaction' he will create it as I tell him to do but he won't create the 'claimant moderated resultselectedPolicyTitle' because it comes next in the iteration. Same logic for the rest of columns.
cols = ['Moderation Queue Title', 'Object ID', 'Moderator', 'Appeal Status', 'Tag', 'claimant moderated resultaction', 'claimant moderated resultselectedPolicyTitle', 'respondent Sampling Informationaction', 'respondent Sampling InformationselectedPolicyTitle', 'Sampling Time']
def transformations(df):
for k, v in df.items():
df[k] = df[k].dropna(axis=1, how='all')
df[k].columns = np.where(df[k].loc[1] == df[k].loc[0], df[k].loc[0], df[k].loc[0]+df[k].loc[1])
df[k] = df[k].drop([df[k].index[0], df[k].index[1]])
if 'Moderation Queue Title' not in df[k]:
df[k]['Moderation Queue Title'] = ""
elif 'Object ID' not in df[k]:
df[k]['Object ID'] = ""
elif 'Moderator' not in df[k]:
df[k]['Moderator'] = ""
elif 'Appeal Status' not in df[k]:
df[k]['Appeal Status'] = ""
elif 'Tag' not in df[k]:
df[k]['Tag'] = ""
elif 'claimant moderated resultaction' not in df[k]:
df[k]['claimant moderated resultaction'] = ""
elif 'claimant moderated resultselectedPolicyTitle' not in df[k]:
df[k]['claimant moderated resultselectedPolicyTitle'] = ""
elif 'respondent Sampling Informationaction' not in df[k]:
df[k]['respondent Sampling Informationaction'] = ""
elif 'respondent Sampling InformationselectedPolicyTitle' not in df[k]:
df[k]['respondent Sampling InformationselectedPolicyTitle'] = ""
elif 'Sampling Time' not in df[k]:
df[k]['Sampling Time'] = ""
elif set(cols).issubset(df[k].columns):
df[k] = df[k][cols]
else:
df[k] = df[k][cols]
I am probably doing something wrong here, can you please point out me what I am missing or provide an alternative approach?
Solution 1:[1]
Your code finds only the first missing column, it creates it and ignores the remaining conditions.
elif == else if
a = 5
if a > 0:
print("a > 0")
elif a > 1:
print("a > 1")
Result:
> a > 0
If you want to check all of the possible missing columns, just use regular ifs.
a = 5
if a > 0:
print("a > 0")
if a > 1:
print("a > 1")
Result:
> a > 0
> a > 1
Solution 2:[2]
It's working properly, it is doing exactly what it should do!
The whole chain of if-elif-elif-elif-else executes ONLY ONE branch. The first one which is True or, if none is true, then else.
Note that elif is a short of else if.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tõnis Piip |
| Solution 2 |
