101 Pandas Exercises for Data Analysis
101 python pandas exercises are designed to challenge your logical muscle and to help internalize data manipulation with python’s favorite package for data analysis. The questions are of 3 levels of difficulties with L1 being the easiest to L3 being the hardest.
101 Pandas Exercises. Photo by Chester Ho.
You might also like to practice the 101 NumPy exercises, they are often used together.
UPDATE from Author: Try the interactive version of this pandas exercises, where you can solve the exercises and run the python code without leaving the page. Hope you will like it!
1. How to import pandas and check the version?
Show Solution
2. How to create a series from a list, numpy array and dict?
Create a pandas series from each of the items below: a list, numpy and a dictionary
Input
Show Solution
3. How to convert the index of a series into a column of a dataframe?
Difficulty Level: L1
Convert the series ser into a dataframe with its index as another column on the dataframe.
Input
Show Solution
4. How to combine many series to form a dataframe?
Difficulty Level: L1
Combine ser1 and ser2 to form a dataframe.
Input
Show Solution
5. How to assign name to the series’ index?
Difficulty Level: L1
Give a name to the series ser calling it ‘alphabets’.
Input
Show Solution
6. How to get the items of series A not present in series B?
Difficulty Level: L2
From ser1 remove items present in ser2.
Show Solution
7. How to get the items not common to both series A and series B?
Difficulty Level: L2
Get all items of ser1 and ser2 not common to both.
Input
Show Solution
8. How to get the minimum, 25th percentile, median, 75th, and max of a numeric series?
Difficuty Level: L2
Compute the minimum, 25th percentile, median, 75th, and maximum of ser.
Input
Show Solution
9. How to get frequency counts of unique items of a series?
Difficulty Level: L1
Calculte the frequency counts of each unique value ser.
Input
Show Solution
10. How to keep only top 2 most frequent values as it is and replace everything else as ‘Other’?
Difficulty Level: L2
From ser, keep the top 2 most frequent items as it is and replace everything else as ‘Other’.
Input
Show Solution
11. How to bin a numeric series to 10 groups of equal size?
Difficulty Level: L2
Bin the series ser into 10 equal deciles and replace the values with the bin name.
Input
Desired Output
# First 5 items
0 7th
1 9th
2 7th
3 3rd
4 8th
dtype: category
Categories (10, object): [1st < 2nd < 3rd < 4th ... 7th < 8th < 9th < 10th]
Show Solution
12. How to convert a numpy array to a dataframe of given shape? (L1)
Difficulty Level: L1
Reshape the series ser into a dataframe with 7 rows and 5 columns
Input
Show Solution
13. How to find the positions of numbers that are multiples of 3 from a series?
Difficulty Level: L2
Find the positions of numbers that are multiples of 3 from ser.
Input
Show Solution
14. How to extract items at given positions from a series
Difficulty Level: L1
From ser, extract the items at positions in list pos.
Input
Show Solution
15. How to stack two series vertically and horizontally ?
Difficulty Level: L1
Stack ser1 and ser2 vertically and horizontally (to form a dataframe).
Input
Show Solution
# Input
ser1 = pd.Series(range(5))
ser2 = pd.Series(list('abcde'))
# Output
# Vertical
ser1.append(ser2)
# Horizontal
df = pd.concat([ser1, ser2], axis=1)
print(df)
#> 0 1
#> 0 0 a
#> 1 1 b
#> 2 2 c
#> 3 3 d
#> 4 4 e
16. How to get the positions of items of series A in another series B?
Difficulty Level: L2
Get the positions of items of ser2 in ser1 as a list.
Input
Show Solution
17. How to compute the mean squared error on a truth and predicted series?
Difficulty Level: L2
Compute the mean squared error of truth and pred series.
Input
Show Solution
18. How to convert the first character of each element in a series to uppercase?
Difficulty Level: L2
Change the first character of each word to upper case in each word of ser.
Show Solution
19. How to calculate the number of characters in each word in a series?
Difficulty Level: L2
Input
Show Solution
20. How to compute difference of differences between consequtive numbers of a series?
Difficulty Level: L1
Difference of differences between the consequtive numbers of ser.
Input
Desired Output
[nan, 2.0, 3.0, 4.0, 5.0, 6.0, 6.0, 8.0]
[nan, nan, 1.0, 1.0, 1.0, 1.0, 0.0, 2.0]
Show Solution
21. How to convert a series of date-strings to a timeseries?
Difficiulty Level: L2
Input
Desired Output
0 2010-01-01 00:00:00
1 2011-02-02 00:00:00
2 2012-03-03 00:00:00
3 2013-04-04 00:00:00
4 2014-05-05 00:00:00
5 2015-06-06 12:20:00
dtype: datetime64[ns]
Show Solution
# Input
ser = pd.Series(['01 Jan 2010', '02-02-2011', '20120303', '2013/04/04', '2014-05-05', '2015-06-06T12:20'])
# Solution 1
from dateutil.parser import parse
ser.map(lambda x: parse(x))
# Solution 2
pd.to_datetime(ser)
#> 0 2010-01-01 00:00:00
#> 1 2011-02-02 00:00:00
#> 2 2012-03-03 00:00:00
#> 3 2013-04-04 00:00:00
#> 4 2014-05-05 00:00:00
#> 5 2015-06-06 12:20:00
#> dtype: datetime64[ns]
22. How to get the day of month, week number, day of year and day of week from a series of date strings?
Difficiulty Level: L2
Get the day of month, week number, day of year and day of week from ser.
Input
Desired output
Date: [1, 2, 3, 4, 5, 6]
Week number: [53, 5, 9, 14, 19, 23]
Day num of year: [1, 33, 63, 94, 125, 157]
Day of week: ['Friday', 'Wednesday', 'Saturday', 'Thursday', 'Monday', 'Saturday']
Show Solution
# Input
ser = pd.Series(['01 Jan 2010', '02-02-2011', '20120303', '2013/04/04', '2014-05-05', '2015-06-06T12:20'])
# Solution
from dateutil.parser import parse
ser_ts = ser.map(lambda x: parse(x))
# day of month
print("Date: ", ser_ts.dt.day.tolist())
# week number
print("Week number: ", ser_ts.dt.weekofyear.tolist())
# day of year
print("Day number of year: ", ser_ts.dt.dayofyear.tolist())
# day of week
print("Day of week: ", ser_ts.dt.weekday_name.tolist())
#> Date: [1, 2, 3, 4, 5, 6]
#> Week number: [53, 5, 9, 14, 19, 23]
#> Day num of year: [1, 33, 63, 94, 125, 157]
#> Day of week: ['Friday', 'Wednesday', 'Saturday', 'Thursday', 'Monday', 'Saturday']
23. How to convert year-month string to dates corresponding to the 4th day of the month?
Difficiulty Level: L2
Change ser to dates that start with 4th of the respective months.
Input
Desired Output
0 2010-01-04
1 2011-02-04
2 2012-03-04
dtype: datetime64[ns]
Show Solution
import pandas as pd
# Input
ser = pd.Series(['Jan 2010', 'Feb 2011', 'Mar 2012'])
# Solution 1
from dateutil.parser import parse
# Parse the date
ser_ts = ser.map(lambda x: parse(x))
# Construct date string with date as 4
ser_datestr = ser_ts.dt.year.astype('str') + '-' + ser_ts.dt.month.astype('str') + '-' + '04'
# Format it.
[parse(i).strftime('%Y-%m-%d') for i in ser_datestr]
# Solution 2
ser.map(lambda x: parse('04 ' + x))
#> 0 2010-01-04
#> 1 2011-02-04
#> 2 2012-03-04
#> dtype: datetime64[ns]
24. How to filter words that contain atleast 2 vowels from a series?
Difficiulty Level: L3
From ser, extract words that contain atleast 2 vowels.
Input
Desired Output
0 Apple
1 Orange
4 Money
dtype: object
Show Solution
25. How to filter valid emails from a series?
Difficiulty Level: L3
Extract the valid emails from the series emails. The regex pattern for valid emails is provided as reference.
Input
Desired Output
1 rameses@egypt.com
2 matt@t.co
3 narendra@modi.com
dtype: object
Show Solution
26. How to get the mean of a series grouped by another series?
Difficiulty Level: L2
Compute the mean of weights of each fruit.
Input
fruit = pd.Series(np.random.choice(['apple', 'banana', 'carrot'], 10))
weights = pd.Series(np.linspace(1, 10, 10))
print(weight.tolist())
print(fruit.tolist())
#> [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
#> ['banana', 'carrot', 'apple', 'carrot', 'carrot', 'apple', 'banana', 'carrot', 'apple', 'carrot']
Desired output
# values can change due to randomness
apple 6.0
banana 4.0
carrot 5.8
dtype: float64
Show Solution
27. How to compute the euclidean distance between two series?
Difficiulty Level: L2
Compute the euclidean distance between series (points) p and q, without using a packaged formula.
Input
Desired Output
18.165
Show Solution
28. How to find all the local maxima (or peaks) in a numeric series?
Difficiulty Level: L3
Get the positions of peaks (values surrounded by smaller values on both sides) in ser.
Input
Desired output
array([1, 5, 7])
Show Solution
29. How to replace missing spaces in a string with the least frequent character?
Replace the spaces in my_str with the least frequent character.
Difficiulty Level: L2
Input
Desired Output
'dbccdebcabedcgade' # least frequent is 'c'
Show Solution
30. How to create a TimeSeries starting ‘2000-01-01’ and 10 weekends (saturdays) after that having random numbers as values?
Difficiulty Level: L2
Desired output
# values can be random
2000-01-01 4
2000-01-08 1
2000-01-15 8
2000-01-22 4
2000-01-29 4
2000-02-05 2
2000-02-12 4
2000-02-19 9
2000-02-26 6
2000-03-04 6
Show Solution
31. How to fill an intermittent time series so all missing dates show up with values of previous non-missing date?
Difficiulty Level: L2
ser has missing dates and values. Make all missing dates appear and fill up with value from previous date.
Input
Desired Output
2000-01-01 1.0
2000-01-02 1.0
2000-01-03 10.0
2000-01-04 10.0
2000-01-05 10.0
2000-01-06 3.0
2000-01-07 3.0
2000-01-08 NaN
Show Solution
32. How to compute the autocorrelations of a numeric series?
Difficiulty Level: L3
Compute autocorrelations for the first 10 lags of ser. Find out which lag has the largest correlation.
Input
Desired output
# values will change due to randomness
[0.29999999999999999, -0.11, -0.17000000000000001, 0.46000000000000002, 0.28000000000000003, -0.040000000000000001, -0.37, 0.41999999999999998, 0.47999999999999998, 0.17999999999999999]
Lag having highest correlation: 9
Show Solution
33. How to import only every nth row from a csv file to create a dataframe?
Difficiulty Level: L2
Import every 50th row of BostonHousing dataset as a dataframe.
Show Solution
# Solution 1: Use chunks and for-loop
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/BostonHousing.csv', chunksize=50)
df2 = pd.DataFrame()
for chunk in df:
df2 = df2.append(chunk.iloc[0,:])
# Solution 2: Use chunks and list comprehension
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/BostonHousing.csv', chunksize=50)
df2 = pd.concat([chunk.iloc[0] for chunk in df], axis=1)
df2 = df2.transpose()
# Solution 3: Use csv reader
import csv
with open('BostonHousing.csv', 'r') as f:
reader = csv.reader(f)
out = []
for i, row in enumerate(reader):
if i%50 == 0:
out.append(row)
df2 = pd.DataFrame(out[1:], columns=out[0])
print(df2.head())
#> crim zn indus chas nox rm age \
#> 0 0.21977 0.0 6.91 0 0.44799999999999995 5.602 62.0
#> 1 0.0686 0.0 2.89 0 0.445 7.416 62.5
#> 2 2.7339700000000002 0.0 19.58 0 0.871 5.597 94.9
#> 3 0.0315 95.0 1.47 0 0.40299999999999997 6.975 15.3
#> 4 0.19072999999999998 22.0 5.86 0 0.431 6.718 17.5
#>
#> dis rad tax ptratio b lstat medv
#> 0 6.0877 3 233 17.9 396.9 16.2 19.4
#> 1 3.4952 2 276 18.0 396.9 6.19 33.2
#> 2 1.5257 5 403 14.7 351.85 21.45 15.4
#> 3 7.6534 3 402 17.0 396.9 4.56 34.9
#> 4 7.8265 7 330 19.1 393.74 6.56 26.2
34. How to change column values when importing csv to a dataframe?
Difficulty Level: L2
Import the boston housing dataset, but while importing change the 'medv' (median house value) column so that values < 25 becomes ‘Low’ and > 25 becomes ‘High’.
Show Solution
# Solution 1: Using converter parameter
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/BostonHousing.csv',
converters={'medv': lambda x: 'High' if float(x) > 25 else 'Low'})
# Solution 2: Using csv reader
import csv
with open('BostonHousing.csv', 'r') as f:
reader = csv.reader(f)
out = []
for i, row in enumerate(reader):
if i > 0:
row[13] = 'High' if float(row[13]) > 25 else 'Low'
out.append(row)
df = pd.DataFrame(out[1:], columns=out[0])
print(df.head())
#> crim zn indus chas nox \
#> 0 0.00632 18.0 2.31 0 0.5379999999999999
#> 1 0.02731 0.0 7.07 0 0.469
#> 2 0.02729 0.0 7.07 0 0.469
#> 3 0.032369999999999996 0.0 2.18 0 0.45799999999999996
#> 4 0.06905 0.0 2.18 0 0.45799999999999996
#>
#> rm age dis rad tax ptratio b lstat medv
#> 0 6.575 65.2 4.09 1 296 15.3 396.9 4.98 Low
#> 1 6.421 78.9 4.9671 2 242 17.8 396.9 9.14 Low
#> 2 7.185 61.1 4.9671 2 242 17.8 392.83 4.03 High
#> 3 6.997999999999999 45.8 6.0622 3 222 18.7 394.63 2.94 High
#> 4 7.147 54.2 6.0622 3 222 18.7 396.9 5.33 High
35. How to create a dataframe with rows as strides from a given series?
Difficiulty Level: L3
Input
Desired Output
array([[ 0, 1, 2, 3],
[ 2, 3, 4, 5],
[ 4, 5, 6, 7],
[ 6, 7, 8, 9],
[ 8, 9, 10, 11],
[10, 11, 12, 13]])
Show Solution
36. How to import only specified columns from a csv file?
Difficulty Level: L1
Import ‘crim’ and ‘medv’ columns of the BostonHousing dataset as a dataframe.
Show Solution
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/BostonHousing.csv', usecols=['crim', 'medv'])
print(df.head())
#> crim medv
#> 0 0.00632 24.0
#> 1 0.02731 21.6
#> 2 0.02729 34.7
#> 3 0.03237 33.4
#> 4 0.06905 36.2
37. How to get the nrows, ncolumns, datatype, summary stats of each column of a dataframe? Also get the array and list equivalent.
Difficulty Level: L2
Get the number of rows, columns, datatype and summary statistics of each column of the Cars93 dataset. Also get the numpy array and list equivalent of the dataframe.
Show Solution
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
# number of rows and columns
print(df.shape)
# datatypes
print(df.dtypes)
# how many columns under each dtype
print(df.get_dtype_counts())
print(df.dtypes.value_counts())
# summary statistics
df_stats = df.describe()
# numpy array
df_arr = df.values
# list
df_list = df.values.tolist()
#> (93, 27)
#> Manufacturer object
#> Model object
#> Type object
#> Min.Price float64
#> Price float64
#> Max.Price float64
#> MPG.city float64
#> MPG.highway float64
#> AirBags object
#> DriveTrain object
#> Cylinders object
#> EngineSize float64
#> Horsepower float64
#> RPM float64
#> Rev.per.mile float64
#> Man.trans.avail object
#> Fuel.tank.capacity float64
#> Passengers float64
#> Length float64
#> Wheelbase float64
#> Width float64
#> Turn.circle float64
#> Rear.seat.room float64
#> Luggage.room float64
#> Weight float64
#> Origin object
#> Make object
#> dtype: object
#> float64 18
#> object 9
#> dtype: int64
#> float64 18
#> object 9
#> dtype: int64
38. How to extract the row and column number of a particular cell with given criterion?
Difficulty Level: L1
Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
Which manufacturer, model and type has the highest Price? What is the row and column number of the cell with the highest Price value?
Show Solution
# Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
# Solution
# Get Manufacturer with highest price
df.loc[df.Price == np.max(df.Price), ['Manufacturer', 'Model', 'Type']]
# Get Row and Column number
row, col = np.where(df.values == np.max(df.Price))
# Get the value
df.iat[row[0], col[0]]
df.iloc[row[0], col[0]]
# Alternates
df.at[row[0], 'Price']
df.get_value(row[0], 'Price')
# The difference between `iat` - `iloc` vs `at` - `loc` is:
# `iat` snd `iloc` accepts row and column numbers.
# Whereas `at` and `loc` accepts index and column names.
#> 61.899999999999999
39. How to rename a specific columns in a dataframe?
Difficulty Level: L2
Rename the column Type as CarType in df and replace the ‘.’ in column names with ‘_’.
Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
print(df.columns)
#> Index(['Manufacturer', 'Model', 'Type', 'Min.Price', 'Price', 'Max.Price',
#> 'MPG.city', 'MPG.highway', 'AirBags', 'DriveTrain', 'Cylinders',
#> 'EngineSize', 'Horsepower', 'RPM', 'Rev.per.mile', 'Man.trans.avail',
#> 'Fuel.tank.capacity', 'Passengers', 'Length', 'Wheelbase', 'Width',
#> 'Turn.circle', 'Rear.seat.room', 'Luggage.room', 'Weight', 'Origin',
#> 'Make'],
#> dtype='object')
Desired Solution
print(df.columns)
#> Index(['Manufacturer', 'Model', 'CarType', 'Min_Price', 'Price', 'Max_Price',
#> 'MPG_city', 'MPG_highway', 'AirBags', 'DriveTrain', 'Cylinders',
#> 'EngineSize', 'Horsepower', 'RPM', 'Rev_per_mile', 'Man_trans_avail',
#> 'Fuel_tank_capacity', 'Passengers', 'Length', 'Wheelbase', 'Width',
#> 'Turn_circle', 'Rear_seat_room', 'Luggage_room', 'Weight', 'Origin',
#> 'Make'],
#> dtype='object')
Show Solution
# Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
# Solution
# Step 1:
df=df.rename(columns = {'Type':'CarType'})
# or
df.columns.values[2] = "CarType"
# Step 2:
df.columns = df.columns.map(lambda x: x.replace('.', '_'))
print(df.columns)
#> Index(['Manufacturer', 'Model', 'CarType', 'Min_Price', 'Price', 'Max_Price',
#> 'MPG_city', 'MPG_highway', 'AirBags', 'DriveTrain', 'Cylinders',
#> 'EngineSize', 'Horsepower', 'RPM', 'Rev_per_mile', 'Man_trans_avail',
#> 'Fuel_tank_capacity', 'Passengers', 'Length', 'Wheelbase', 'Width',
#> 'Turn_circle', 'Rear_seat_room', 'Luggage_room', 'Weight', 'Origin',
#> 'Make'],
#> dtype='object')
40. How to check if a dataframe has any missing values?
Difficulty Level: L1
Check if df has any missing values.
Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
Show Solution
# Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
# Solution
df.isnull().values.any()
41. How to count the number of missing values in each column?
Difficulty Level: L2
Count the number of missing values in each column of df. Which column has the maximum number of missing values?
Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
Show Solution
# Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
# Solution
n_missings_each_col = df.apply(lambda x: x.isnull().sum())
n_missings_each_col.argmax()
#> 'Luggage.room'
42. How to replace missing values of multiple numeric columns with the mean?
Difficulty Level: L2
Replace missing values in Min.Price and Max.Price columns with their respective mean.
Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
Show Solution
# Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
# Solution
df_out = df[['Min.Price', 'Max.Price']] = df[['Min.Price', 'Max.Price']].apply(lambda x: x.fillna(x.mean()))
print(df_out.head())
#> Min.Price Max.Price
#> 0 12.900000 18.800000
#> 1 29.200000 38.700000
#> 2 25.900000 32.300000
#> 3 17.118605 44.600000
#> 4 17.118605 21.459091
43. How to use apply function on existing columns with global variables as additional arguments?
Difficulty Level: L3
In df, use apply method to replace the missing values in Min.Price with the column’s mean and those in Max.Price with the column’s median.
Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
Show Solution
# Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
# Solution
d = {'Min.Price': np.nanmean, 'Max.Price': np.nanmedian}
df[['Min.Price', 'Max.Price']] = df[['Min.Price', 'Max.Price']].apply(lambda x, d: x.fillna(d[x.name](x)), args=(d, ))
44. How to select a specific column from a dataframe as a dataframe instead of a series?
Difficulty Level: L2
Get the first column (a) in df as a dataframe (rather than as a Series).
Input
Show Solution
45. How to change the order of columns of a dataframe?
Difficulty Level: L3
Actually 3 questions.
- In
df, interchange columns'a'and'c'. - Create a generic function to interchange two columns, without hardcoding column names.
- Sort the columns in reverse alphabetical order, that is colume
'e'first through column'a'last.
Input
Show Solution
46. How to set the number of rows and columns displayed in the output?
Difficulty Level: L2
Change the pamdas display settings on printing the dataframe df it shows a maximum of 10 rows and 10 columns.
Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
Show Solution
# Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
# Solution
pd.set_option('display.max_columns', 10)
pd.set_option('display.max_rows', 10)
# df
# Show all available options
# pd.describe_option()
47. How to format or suppress scientific notations in a pandas dataframe?
Difficulty Level: L2
Suppress scientific notations like ‘e-03’ in df and print upto 4 numbers after decimal.
Input
Desired Output
#> random
#> 0 0.0035
#> 1 0.0000
#> 2 0.0747
#> 3 0.0000
Show Solution
48. How to format all the values in a dataframe as percentages?
Difficulty Level: L2
Format the values in column 'random' of df as percentages.
Input
Desired Output
#> random
#> 0 68.97%
#> 1 95.72%
#> 2 15.91%
#> 3 2.10%
Show Solution
# Input
df = pd.DataFrame(np.random.random(4), columns=['random'])
# Solution
out = df.style.format({
'random': '{0:.2%}'.format,
})
out
| random | |
|---|---|
| 0 | 21.66% |
| 1 | 44.90% |
| 2 | 85.69% |
| 3 | 92.12% |
49. How to filter every nth row in a dataframe?
Difficulty Level: L1
From df, filter the 'Manufacturer', 'Model' and 'Type' for every 20th row starting from 1st (row 0).
Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
Show Solution
# Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv')
# Solution
print(df.iloc[::20, :][['Manufacturer', 'Model', 'Type']])
#> Manufacturer Model Type
#> 0 Acura Integra Small
#> 20 Chrysler LeBaron Compact
#> 40 Honda Prelude Sporty
#> 60 Mercury Cougar Midsize
#> 80 Subaru Loyale Small
50. How to create a primary key index by combining relevant columns?
Difficulty Level: L2
In df, Replace NaNs with ‘missing’ in columns 'Manufacturer', 'Model' and 'Type' and create a index as a combination of these three columns and check if the index is a primary key.
Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv', usecols=[0,1,2,3,5])
Desired Output
Manufacturer Model Type Min.Price Max.Price
Acura_Integra_Small Acura Integra Small 12.9 18.8
missing_Legend_Midsize missing Legend Midsize 29.2 38.7
Audi_90_Compact Audi 90 Compact 25.9 32.3
Audi_100_Midsize Audi 100 Midsize NaN 44.6
BMW_535i_Midsize BMW 535i Midsize NaN NaN
Show Solution
# Input
df = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/Cars93_miss.csv', usecols=[0,1,2,3,5])
# Solution
df[['Manufacturer', 'Model', 'Type']] = df[['Manufacturer', 'Model', 'Type']].fillna('missing')
df.index = df.Manufacturer + '_' + df.Model + '_' + df.Type
print(df.index.is_unique)
#> True
51. How to get the row number of the nth largest value in a column?
Difficulty Level: L2
Find the row position of the 5th largest value of column 'a' in df.
Input
Show Solution
52. How to find the position of the nth largest value greater than a given value?
Difficulty Level: L2
In ser, find the position of the 2nd largest value greater than the mean.
Input
Show Solution
53. How to get the last n rows of a dataframe with row sum > 100?
Difficulty Level: L2
Get the last two rows of df whose row sum is greater than 100.
Show Solution
54. How to find and cap outliers from a series or dataframe column?
Difficulty Level: L2
Replace all values of ser in the lower 5%ile and greater than 95%ile with respective 5th and 95th %ile value.
Input
Show Solution
55. How to reshape a dataframe to the largest possible square after removing the negative values?
Difficulty Level: L3
Reshape df to the largest possible square with negative values removed. Drop the smallest values if need be. The order of the positive numbers in the result should remain the same as the original.
Input
Show Solution
56. How to swap two rows of a dataframe?
Difficulty Level: L2
Swap rows 1 and 2 in df.
Input
Show Solution
57. How to reverse the rows of a dataframe?
Difficulty Level: L2
Reverse all the rows of dataframe df.
Input
Show Solution
58. How to create one-hot encodings of a categorical variable (dummy variables)?
Difficulty Level: L2
Get one-hot encodings for column 'a' in the dataframe df and append it as columns.
Input
df = pd.DataFrame(np.arange(25).reshape(5,-1), columns=list('abcde'))
a b c d e
0 0 1 2 3 4
1 5 6 7 8 9
2 10 11 12 13 14
3 15 16 17 18 19
4 20 21 22 23 24
Output
0 5 10 15 20 b c d e
0 1 0 0 0 0 1 2 3 4
1 0 1 0 0 0 6 7 8 9
2 0 0 1 0 0 11 12 13 14
3 0 0 0 1 0 16 17 18 19
4 0 0 0 0 1 21 22 23 24
Show Solution
59. Which column contains the highest number of row-wise maximum values?
Difficulty Level: L2
Obtain the column name with the highest number of row-wise maximum’s in df.
Show Solution
60. How to create a new column that contains the row number of nearest column by euclidean distance?
Create a new column such that, each row contains the row number of nearest row-record by euclidean distance.
Difficulty Level: L3
Input
Desired Output
Show Solution
61. How to know the maximum possible correlation value of each column against other columns?
Difficulty Level: L2
Compute maximum possible absolute correlation value of each column against other columns in df.
Input
Show Solution
62. How to create a column containing the minimum by maximum of each row?
Difficulty Level: L2
Compute the minimum-by-maximum for every row of df.
Show Solution
63. How to create a column that contains the penultimate value in each row?
Difficulty Level: L2
Create a new column 'penultimate' which has the second largest value of each row of df.
Input
Show Solution
64. How to normalize all columns in a dataframe?
Difficulty Level: L2
- Normalize all columns of
dfby subtracting the column mean and divide by standard deviation. - Range all columns of
dfsuch that the minimum value in each column is 0 and max is 1.
Don’t use external packages like sklearn.
Input
Show Solution
65. How to compute the correlation of each row with the suceeding row?
Difficulty Level: L2
Compute the correlation of each row of df with its succeeding row.
Input
Show Solution
66. How to replace both the diagonals of dataframe with 0?
Difficulty Level: L2
Replace both values in both diagonals of df with 0.
Input
Desired output
Show Solution
67. How to get the particular group of a groupby dataframe by key?
Difficulty Level: L2
This is a question related to understanding of grouped dataframe. From df_grouped, get the group belonging to 'apple' as a dataframe.
Input
68. How to get the n’th largest value of a column when grouped by another column?
Difficulty Level: L2
In df, find the second largest value of 'taste' for 'banana'
Input
Show Solution
69. How to compute grouped mean on pandas dataframe and keep the grouped column as another column (not index)?
Difficulty Level: L1
In df, Compute the mean price of every fruit, while keeping the fruit as another column instead of an index.
Input
Show Solution
70. How to join two dataframes by 2 columns so they have only the common rows?
Difficulty Level: L2
Join dataframes df1 and df2 by ‘fruit-pazham’ and ‘weight-kilo’.
Input
Show Solution
# Input
df1 = pd.DataFrame({'fruit': ['apple', 'banana', 'orange'] * 3,
'weight': ['high', 'medium', 'low'] * 3,
'price': np.random.randint(0, 15, 9)})
df2 = pd.DataFrame({'pazham': ['apple', 'orange', 'pine'] * 2,
'kilo': ['high', 'low'] * 3,
'price': np.random.randint(0, 15, 6)})
# Solution
pd.merge(df1, df2, how='inner', left_on=['fruit', 'weight'], right_on=['pazham', 'pounds'], suffixes=['_left', '_right'])
| fruit | price_left | weight | pazham | pounds | price_right | |
|---|---|---|---|---|---|---|
| 0 | apple | 5 | high | apple | high | 11 |
| 1 | apple | 10 | high | apple | high | 11 |
| 2 | apple | 8 | high | apple | high | 11 |
| 3 | orange | 6 | low | orange | low | 6 |
| 4 | orange | 7 | low | orange | low | 6 |
| 5 | orange | 0 | low | orange | low | 6 |
71. How to remove rows from a dataframe that are present in another dataframe?
Difficulty Level: L3
From df1, remove the rows that are present in df2. All three columns must be the same.
Input
Show Solution
72. How to get the positions where values of two columns match?
Difficulty Level: L2
Show Solution
73. How to create lags and leads of a column in a dataframe?
Difficulty Level: L2
Create two new columns in df, one of which is a lag1 (shift column a down by 1 row) of column ‘a’ and the other is a lead1 (shift column b up by 1 row).
Input
df = pd.DataFrame(np.random.randint(1, 100, 20).reshape(-1, 4), columns = list('abcd'))
a b c d
0 66 34 76 47
1 20 86 10 81
2 75 73 51 28
3 1 1 9 83
4 30 47 67 4
Desired Output
a b c d a_lag1 b_lead1
0 66 34 76 47 NaN 86.0
1 20 86 10 81 66.0 73.0
2 75 73 51 28 20.0 1.0
3 1 1 9 83 75.0 47.0
4 30 47 67 4 1.0 NaN
Show Solution
74. How to get the frequency of unique values in the entire dataframe?
Difficulty Level: L2
Get the frequency of unique values in the entire dataframe df.
Input
Show Solution
75. How to split a text column into two separate columns?
Difficulty Level: L2
Split the string column in df to form a dataframe with 3 columns as shown.
Input
Desired Output
0 STD City State
1 33 Kolkata West Bengal
2 44 Chennai Tamil Nadu
3 40 Hyderabad Telengana
4 80 Bangalore Karnataka
Show Solution
To be continued . .