PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python Exercises » Python Pandas Exercise

Python Pandas Exercise

Updated on: March 9, 2021 | 40 Comments

Python Pandas Exercise

This Pandas exercise project will help Python developers to learn and practice pandas. Pandas is an open-source, BSD-licensed Python library. Pandas is a handy and useful data-structure tool for analyzing large and complex data.

Practice DataFrame, Data Selection, Group-By, Series, Sorting, Searching, statistics. Practice Data analysis using Pandas.

In this exercise, we are using Automobile Dataset for data analysis. This Dataset has different characteristics of an auto such as body-style, wheel-base, engine-type, price, mileage, horsepower, etc.

Automobile_data setDownload Automobile Dataset

Also Read:

  • Pandas DataFrame

What included in this Pandas exercise?

  • It contains 10 questions. The solution is provided for each question.
  • Each question includes a specific Pandas topic you need to learn.

When you complete each question, you get more familiar with data analysis using pandas.

Exercise 1: From the given dataset print the first and last five rows

Expected Output:

Python Pandas printing first 5 rows
Python Pandas printing first 5 rows
Python Pandas printing last 5 rows
Python Pandas printing last 5 rows
Show Solution

Print first five rows

import pandas as pd
df = pd.read_csv("D:\\Python\\Articles\\pandas\\automobile-dataset\\Automobile_data.csv")
df.head(5)

Print last five rows

import pandas as pd
df = pd.read_csv("D:\\Python\\Articles\\pandas\\automobile-dataset\\Automobile_data.csv")
df.tail(5)

Exercise 2: Clean the dataset and update the CSV file

Replace all column values which contain ?, n.a, or NaN.

Show Solution
df = pd.read_csv("D:\\Python\\Articles\\pandas\\automobile-dataset\\Automobile_data.csv", na_values={
'price':["?","n.a"],
'stroke':["?","n.a"],
'horsepower':["?","n.a"],
'peak-rpm':["?","n.a"],
'average-mileage':["?","n.a"]})
print (df)

df.to_csv("D:\\Python\\Articles\\pandas\\automobile-dataset\\Automobile_data.csv")

Exercise 3: Find the most expensive car company name

Print most expensive car’s company name and price.

Expected Output:

Python Pandas printing most costly car name
Python Pandas printing most costly car name
Show Solution
import pandas as pd
df = pd.read_csv("D:\\Python\\Articles\\pandas\\automobile-dataset\\Automobile_data.csv")
df = df [['company','price']][df.price==df['price'].max()]
df

Exercise 4: Print All Toyota Cars details

Expected Output:

Python Pandas printing all Toyota cars data
Python Pandas printing all Toyota cars data
Show Solution
import pandas as pd
df = pd.read_csv("D:\\Python\\Articles\\pandas\\automobile-dataset\\Automobile_data.csv")
car_Manufacturers = df.groupby('company')
toyotaDf = car_Manufacturers.get_group('toyota')
toyotaDf

Exercise 5: Count total cars per company

Expected Outcome:

Python Pandas count total cars per company
Python Pandas count total cars per company
Show Solution
import pandas as pd
df = pd.read_csv("D:\\Python\\Articles\\pandas\\automobile-dataset\\Automobile_data.csv")
df['company'].value_counts()

Exercise 6: Find each company’s Higesht price car

Expected Outcome:

Python Pandas printing each company's highest price car
Show Solution
import pandas as pd
df = pd.read_csv("D:\\Python\\Articles\\pandas\\automobile-dataset\\Automobile_data.csv")
car_Manufacturers = df.groupby('company')
priceDf = car_Manufacturers['company','price'].max()
priceDf

Exercise 7: Find the average mileage of each car making company

Expected Output:

Python Pandas printing average mileage of each car making company
Python Pandas printing average mileage of each car making company
Show Solution
import pandas as pd
df = pd.read_csv("D:\\Python\\Articles\\pandas\\automobile-dataset\\Automobile_data.csv")
car_Manufacturers = df.groupby('company')
mileageDf = car_Manufacturers['company','average-mileage'].mean()
mileageDf

Exercise 8: Sort all cars by Price column

Expected Output:

Python Pandas sort all cars by price column
Python Pandas sort all cars by price column
Show Solution
import pandas as pd
carsDf = pd.read_csv("D:\\Python\\Articles\\pandas\\automobile-dataset\\Automobile_data.csv")
carsDf = carsDf.sort_values(by=['price', 'horsepower'], ascending=False)
carsDf.head(5)

Exercise 9: Concatenate two data frames using the following conditions

Create two data frames using the following two dictionaries.

GermanCars = {'Company': ['Ford', 'Mercedes', 'BMV', 'Audi'], 'Price': [23845, 171995, 135925 , 71400]}
japaneseCars = {'Company': ['Toyota', 'Honda', 'Nissan', 'Mitsubishi '], 'Price': [29995, 23600, 61500 , 58900]}

Expected Output:

Python Pandas concatenate two data frames and create key for each data frame
Python Pandas concatenate two data frames and create a key for each data frame
Show Solution
import pandas as pd

GermanCars = {'Company': ['Ford', 'Mercedes', 'BMV', 'Audi'], 'Price': [23845, 171995, 135925 , 71400]}
carsDf1 = pd.DataFrame.from_dict(GermanCars)

japaneseCars = {'Company': ['Toyota', 'Honda', 'Nissan', 'Mitsubishi '], 'Price': [29995, 23600, 61500 , 58900]}
carsDf2 = pd.DataFrame.from_dict(japaneseCars)

carsDf = pd.concat([carsDf1, carsDf2], keys=["Germany", "Japan"])
carsDf

Exercise 10: Merge two data frames using the following condition

Create two data frames using the following two Dicts, Merge two data frames, and append the second data frame as a new column to the first data frame.

Car_Price = {'Company': ['Toyota', 'Honda', 'BMV', 'Audi'], 'Price': [23845, 17995, 135925 , 71400]}
car_Horsepower = {'Company': ['Toyota', 'Honda', 'BMV', 'Audi'], 'horsepower': [141, 80, 182 , 160]}

Expected Output:

Python Pandas merge two data frames and append new data frame as new column
Python Pandas merge two data frames and append new data frame as a new column
Show Solution
import pandas as pd

Car_Price = {'Company': ['Toyota', 'Honda', 'BMV', 'Audi'], 'Price': [23845, 17995, 135925 , 71400]}
carPriceDf = pd.DataFrame.from_dict(Car_Price)

car_Horsepower = {'Company': ['Toyota', 'Honda', 'BMV', 'Audi'], 'horsepower': [141, 80, 182 , 160]}
carsHorsepowerDf = pd.DataFrame.from_dict(car_Horsepower)

carsDf = pd.merge(carPriceDf, carsHorsepowerDf, on="Company")
carsDf

Filed Under: Pandas, Python, Python Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Pandas Python Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Comments

  1. Sandeep says

    February 15, 2022 at 4:58 am

    Exercises are good but waay too easy… please post some more exercises with increased difficulty. Thanks 🙂

    Reply
  2. Kunal Sarkar says

    January 2, 2022 at 10:58 pm

    Sir I want more to practice please provide more question

    Reply
  3. Pri says

    October 26, 2021 at 5:11 am

    Nicely explained set of practice problems. Thank you.

    Reply
  4. Chari Manepalli says

    October 12, 2021 at 1:07 pm

    great boosts up, thanks for the exercises,

    Reply
    • Vishal says

      October 21, 2021 at 4:44 pm

      You’re welcome, Chari Manepalli.

      Reply
  5. Menderes Karakaş says

    June 16, 2021 at 6:13 am

    these exercises are very helpful thanks for your work. I will definitely look for other exercises too. I you are healthy. Lots of love.

    Reply
  6. Harry says

    April 25, 2021 at 3:38 pm

    Thanks for sharing this! It was super helpful for me to get the basics of pandas! Keep up the share <3

    Reply
  7. Sandeep Mallela says

    April 17, 2021 at 8:54 pm

    Hi Vishal, this is a good exercise. Thanks for providing this. However, I couldn’t execute exercise 4 with the given code.

    Reply
  8. REFAAT says

    April 7, 2021 at 11:24 pm

    Very excellent explanation
    Thank you my friend

    Reply
  9. Dohyun Jung says

    March 7, 2021 at 11:46 am

    Super! Ultra! Great! Python Tutorial!

    Reply
    • Vishal says

      March 9, 2021 at 8:09 pm

      Thank you, Dohyun Jung.

      Reply
  10. User1234 says

    January 31, 2021 at 11:59 pm

    Thank you very much! Super helpful at the first steps with pandas.

    Reply
  11. AMANJOT SINGH says

    January 29, 2021 at 8:38 am

    thanks alot, it really helps me out to exercise

    Reply
    • Vishal says

      January 31, 2021 at 10:11 am

      You’re welcome, Amanjot.

      Reply
  12. ivansaul says

    December 27, 2020 at 1:28 pm

    for question 7:

    company_grp=df.groupby('company')
    company_grp.agg({
        'average-mileage':np.mean
    })
    Reply
  13. Meet says

    December 8, 2020 at 5:59 pm

    About Question 6: Find each company’s Higesht price car

    This solution code will return max value of all the columns that we include to be printed. So, for example, if I add wheel-base column, then the wheel-base value corresponding to the mercedes-benz company will be 120.9 instead of the 112 which corresponds to the row with max price 45400.

    Any way to do this?

    Reply
  14. Ramajayam says

    November 13, 2020 at 10:21 pm

    Good practice for me. Thank you.

    Reply
  15. Sara says

    October 19, 2020 at 6:12 pm

    It was helpful, thanks!

    Reply
    • Vishal says

      October 20, 2020 at 2:51 pm

      You’re welcome, Sara.

      Reply
  16. Janesh says

    September 3, 2020 at 6:15 pm

    Wow.
    This exercise helped me a lot in reinforcing the concepts.
    Found no issues with this exercise.It is great.
    Just need more such exercises to practice.

    Reply
    • Vishal says

      September 5, 2020 at 10:13 pm

      Thank you, Janesh.

      Reply
  17. Dingus Bingus says

    July 24, 2020 at 12:55 am

    Exercise 2 could be better. There’s no null values in the data to begin with.

    Reply
  18. Kishan Singh says

    July 14, 2020 at 1:45 am

    Nice exercise please add more such exercises

    Reply
  19. Jadiel Ncube says

    June 13, 2020 at 4:49 am

    Question 3.

    df=df.groupby(["company"]).sum().sort_values("price", ascending=False)
    df
    Reply
  20. Noel danton says

    May 29, 2020 at 9:44 pm

    could you provide the link to the data please, preferably in CSV format it would be a real help so that we work with the real data, otherwise great job overall thank you.

    Reply
    • Vishal says

      May 31, 2020 at 11:21 am

      Hey Noel Danton, Please download this Automobile Data Set

      Reply
  21. vinay says

    May 19, 2020 at 3:21 pm

    This exercise is really helpful it helps in reminding and and working with all the functions at
    once. i hope you will add more no of exercise in the practice series.

    Reply
  22. tushar says

    May 15, 2020 at 12:26 pm

    can you please add isnull functionality with data sets ?

    Reply
  23. Gaurav Sharma says

    May 10, 2020 at 6:37 pm

    for question 4:

    import pandas as pd
    df=pd.DataFrame(pd.read_csv(r'path.csv'))
    df[(df.company == 'toyota')]
    

    Great content 🙂

    Reply
  24. sonal says

    May 5, 2020 at 2:09 am

    hi where I will get tutorial on pandas library for beginners with explanation.

    Reply
    • Vishal says

      May 7, 2020 at 8:37 pm

      Hey Sonal you can read pandas documentation

      Reply
  25. jenish dev says

    April 9, 2020 at 11:26 am

    I learned your pythonmysql, it was good. could you do a tutorial on pandas

    Reply
    • Vishal says

      April 10, 2020 at 3:58 pm

      Thank you for your suggestions, Jenish dev

      Reply
  26. Manuel Juarez says

    April 9, 2020 at 2:45 am

    Hi Vishal, is there any possibility we can practice online with this data. Thank you very much

    Reply
    • Vishal says

      April 10, 2020 at 4:02 pm

      Hey Manuel Juarez, unfortunately, we don’t have this feature right now. we are planning to add the interactive exercises in coming months

      Reply
  27. Girish says

    April 7, 2020 at 1:11 pm

    Very Very useful excercises sir. Please add few more questions around the same lines of pandas and datafram. You can raise the complexity level as well. please provide similar excercises on EDA(Binning, Missing Values, Outlier treatment etc.)

    May God Bless you.

    Reply
    • Vishal says

      April 8, 2020 at 2:53 pm

      Hey Girish, I appreciate your kind words, thank you. And, Yes I will add more such exercises with complex problems.

      Reply
    • Sahil Jain says

      May 22, 2020 at 6:01 pm

      Hii, this exercise is really very helpful while learning pandas.
      I don’t understand solution of question 3.
      Can u please explain the solution of question no. 3 ?

      Reply
  28. Vishnu Konjeti says

    March 29, 2020 at 4:36 pm

    This exercise is very helpful in practising Pandas.
    Please add some more datasets and exercises.

    Reply
    • Vishal says

      March 30, 2020 at 6:06 pm

      Thank you, Vishnu Konjeti. yes sure I will add new datasets and exercises

      Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your code </pre>

Posted In

Pandas Python Python Exercises
TweetF  sharein  shareP  Pin

 Python Exercises

  • Python Exercises Home
  • Basic Exercise for Beginners
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2022 pynative.com