﻿ Python Pandas Exercise for Class XII

## Python Pandas Exercise

#### Question 1: From a dataframe show first and last five rows?

``````
Solution
First five rows
import pandas as pd
Result

Last Five Rows
df.tail(5)
Result

```
```

#### Question 2: Clean CSV data and update the file?

``````
Solution
'price':["?","n.a"],
'stroke':["?","n.a"],
'horsepower':["?","n.a"],
'peak-rpm':["?","n.a"],
'mileage':["?","n.a"]})
print (df)

df.to_csv("D:\\DZONE\\Python\\pandas\\Cars_Data.csv")

```
```

#### Question 3: Find which car brand price is maximun?

Find Car Firm with highest rate

``````
Solution

df = df [['brand','price']][df.price==df['price'].max()]
print(df)
o/p

```
```

#### Question 4: find All "nissan" Cars informations?

``````
Solution

car_Comp = df.groupby('brand')
nisDf = car_Comp.get_group('nissan')
print(nisDf)
o/p

```
```

#### Question 5: let calculate total no. of cars per firm?

``````
Solution
df['brand'].value_counts()
o/p

```
```

#### Question 6: Find each brand’s Highest price car?

``````
Solution

car_comp = df.groupby('brand')
priceDf = car_comp['brand','price'].max()
priceDf
Result

```
```

#### Question 7: Find the average mileage of each car brand?

``````
o/p

carComp = df.groupby('brand')
mDf = carComp['brand','mileage'].mean()
print(mDf)
Result

```
```

#### Question 8: Sort all cars by Price?

``````
o/p

Df = Df.sort_values(by=['price', 'horsepower'], ascending=False)
Result

```
```

#### Question 9: Concatenate two data frames and make a key for each data frame?

-

``````
G_Comp = {'Firm': ['Hundai', 'Mazda', 'jaguar', 'Porsche'], 'Price': [18752, 127850, 356982 , 56892]}
J_Comp = {'Firm': ['Porsche', 'Honda', 'Nissan', 'volkswagen'], 'Price': [41781, 25841, 83256 , 56781]}
```
```
``````
O/p

G_Comp = {'Firm': ['Hundai', 'Mazda', 'jaguar', 'Porsche'], 'Price': [18752, 127850, 356982 , 56892]}
carsDf1 = pd.DataFrame.from_dict(G_Comp)

J_Comp = {'Firm': ['Porsche', 'Honda', 'Nissan', 'volkswagen'], 'Price': [41781, 25841, 83256 , 56781]}
carsDf2 = pd.DataFrame.from_dict(J_Comp)

carsDf = pd.concat([carsDf1, carsDf2], keys=["Russia", "India"])
print(carsDf)
Result

```
```

#### Question 10: Merge two data frames using following condition?

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

``````
Price = {'Firm': ['Hundai', 'Honda', 'Chevrolet', 'Porsche'], 'Price': [18752, 17995, 356982 , 56892]}
Hpower = {'Firm': ['Hundai', 'Honda', 'Chevrolet', 'Porsche'], 'horsepower': [141, 80, 182 , 160]}
```
```
``````
Code

Price = {'Firm': ['Hundai', 'Honda', 'Chevrolet', 'Porsche'], 'Price': [18051, 17095, 450982 , 50392]}
pDf = pd.DataFrame.from_dict(Price)

Hpower = {'Firm': ['Hundai', 'Honda', 'Chevrolet', 'Porsche'], 'horsepower': [132, 90, 172 , 150]}
hDf = pd.DataFrame.from_dict(Hpower)

carsDf = pd.merge(pDf, hDf, on="Firm")
carsDf
Result

```
```