'How to Iterate with python dataframe
I'm trying to iterate in my data frame and create a column with the result
import pandas as pd
data = {'Name': ['Mary', 'Jose', 'John', 'Marc', 'Ruth','Rachel'],
'Grades': [10, 8, 8, 5, 7,4],
'Gender':['Female','Male','Male','Male','Female','Female']
}
df = pd.DataFrame(data)
values = []
for x in df.iteritems():
values.append('Passed' if x.Grades < 7 else 'Failed')
df['Final_result'] = values
df
I'm getting 'tuple' object that has no attribute 'Grades'. Can you guys help me?
Solution 1:[1]
If you want to be good at pandas, avoid loops and start thinking "vectorized operations":
import numpy as np
df["Final_result"] = np.where(df["Grades"] < 7, "Passed", "Failed")
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 | Code Different |
