Home > OS >  Try and Except for multivariables
Try and Except for multivariables

Time:07-30

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

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?

CodePudding user response:

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'
  • Related