Issue
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?
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'
Answered By - Barmar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.