Assign variables to a pandas dataframe when specific cell is empty

Question:

I am assigning some variables to values from a data frame.
The data frame 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

if one name or more names are missing or it’s defined as an empty string like here. I would like to assign a variable whenever there is an empty string

Asked By: Omar

||

Answers:

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'
Answered By: Barmar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.