Informatics Practices
Consider the following dataframe, and answer the questions given below:
import pandas as pd
df = pd.DataFrame( { "Quarter1": [2000, 4000, 5000, 4400, 10000],
"Quarter2": [5800, 2500, 5400, 3000, 2900],
"Quarter3": [20000, 16000, 7000, 3600, 8200],
"Quarter4": [1400, 3700, 1700, 2000, 6000]})
(i) Write the code to find mean value from above dataframe df over the index and column axis.
(ii) Use sum() function to find the sum of all the values over the index axis.
Answer
(i)
import pandas as pd
df = pd.DataFrame( { "Quarter1": [2000, 4000, 5000, 4400, 10000],
"Quarter2": [5800, 2500, 5400, 3000, 2900],
"Quarter3": [20000, 16000, 7000, 3600, 8200],
"Quarter4": [1400, 3700, 1700, 2000, 6000]})
mean_over_columns = df.sum(axis=1) / df.count(axis=1)
print("Mean over columns: \n", mean_over_columns)
mean_over_rows = df.sum(axis=0) / df.count(axis=0)
print("Mean over rows: \n", mean_over_rows)
Output
Mean over columns:
0 7300.0
1 6550.0
2 4775.0
3 3250.0
4 6775.0
dtype: float64
Mean over rows:
Quarter1 5080.0
Quarter2 3920.0
Quarter3 10960.0
Quarter4 2960.0
dtype: float64
(ii)
import pandas as pd
df = pd.DataFrame( { "Quarter1": [2000, 4000, 5000, 4400, 10000],
"Quarter2": [5800, 2500, 5400, 3000, 2900],
"Quarter3": [20000, 16000, 7000, 3600, 8200],
"Quarter4": [1400, 3700, 1700, 2000, 6000]})
sum_over_index = df.sum(axis=0)
print("Sum over index (columns):\n", sum_over_index)
Output
Sum over index (columns):
Quarter1 25400
Quarter2 19600
Quarter3 54800
Quarter4 14800
dtype: int64
Related Questions
Consider the given DataFrame 'Genre' :
No Type Code 0 Fiction F 1 Non-fiction NF 2 Drama D 3 Poetry P Write suitable Python statements for the following :
(i) Add a column called Num_Copies with the following data : [300, 290, 450, 760].
(ii) Add a new genre of type 'Folk Tale' having code as "FT" and 600 number of copies.
(iii) Rename the column 'Code' to 'Book_Code'.
Write a program in Python Pandas to create the following DataFrame batsman from a Dictionary :
B_NO Name Score1 Score2 1 Sunil Pillai 90 80 2 Gaurav Sharma 65 45 3 Piyush Goel 70 90 4 Karthik Thakur 80 76 Perform the following operations on the DataFrame :
(i) Add both the scores of a batsman and assign to column "Total".
(ii) Display the highest score in both Score1 and Score2 of the DataFrame.
(iii) Display the DataFrame.
Write the use of the rename(mapper = <dict-like>, axis = 1) method for a Pandas Dataframe. Can the mapper and columns parameter be used together in a rename() method ?
Find the error in the following code ? Suggest the solution.
>>> topDfRollNo Name Marks Sec A 115 Pavni 97.5 Sec B 236 Rishi 98.0 Sec C 307 Preet 98.5 Sec D 422 Paula 98.0topDf.del['Sec D']