Question: Using iterrows ( ) to iterate over every observation of a Pandas DataFrame is easy to understand, but not very efficient. On every iteration, you're
Using iterrows to iterate over every observation of a Pandas DataFrame is easy to understand, but not very efficient. On every iteration, you're creating a new Pandas Series.
If you want to add a column to a DataFrame by calling a function on another column, the iterrows method in combination with a for loop is not the preferred way to go Instead, you'll want to use apply
Compare the iterrows version with the apply version to get the same result in the brics DataFrame:
for lab, row in brics.iterrows :
brics.loclab "namelength" lenrowcountry
bricsnamelength" bricscountryapplylen
We can do a similar thing to call the upper method on every name in the country column. However, upper is a method, so we'll need a slightly different approach:
Instructions
XP
Replace the for loop with a oneliner that uses applystrupper The call should give the same result: a column COUNTRY should be added to cars, containing an uppercase version of the country names.
As usual, print out cars to see the fruits of your hard labor
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
