Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Try and Except for multivariables

I am reading every row in a dataframe and assigning its values in each column to the variables
The dataframe created using this code

data = [['tom', 10], ["", 15], ['juli', 14]]
df = pd.DataFrame(data, columns=['Name', 'Age'])

So after using data.head()

    Name    Age
0   tom     10
1           15
2   juli    14

I want to assign every name to a local variable but what if one name is missing like here how can I do a try and except for this value to assign it automatically 0

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

try:
    name1 = ...
    name2 = ... #What is missing
    name3 = ...
except:
    name2 = "Not available"

Remember that if its another name not necessary name 2, what can I do here?

>Solution :

You can’t use try/except since assigning an empty string isn’t an error.

Just check the value being assigned, and replace it with Not available when it’s empty.

name1 = df.iloc[0]['Name'] or 'Not available'
name2 = df.iloc[1]['Name'] or 'Not available'
name3 = df.iloc[2]['Name'] or 'Not available'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading