CBSE Class 12 Informatics Practices Question 15 of 21

Python Pandas — II — Question 3

Back to all questions
3
Question

Question 3

Write a program that performs count, sum, max, and min functions :

  • On rows

  • On columns

Solution
import pandas as pd
data = {
    'A': [1, 2, 3],
    'B': [4, 5, 6],
    'C': [7, 8, 9]
}

df = pd.DataFrame(data)
print("Operations on rows:")
print("Count:")
print(df.count(axis=1))
print("Sum:")
print(df.sum(axis=1))
print("Max:")
print(df.max(axis=1))
print("Min:")
print(df.min(axis=1))

print("\nOperations on columns:")
print("Count:")
print(df.count())
print("Sum:")
print(df.sum())
print("Max:")
print(df.max())
print("Min:")
print(df.min())
Output
Operations on rows:
Count:
0    3
1    3
2    3
dtype: int64
Sum:
0    12
1    15
2    18
dtype: int64
Max:
0    7
1    8
2    9
dtype: int64
Min:
0    1
1    2
2    3
dtype: int64

Operations on columns:
Count:
A    3
B    3
C    3
dtype: int64
Sum:
A     6
B    15
C    24
dtype: int64
Max:
A    3
B    6
C    9
dtype: int64
Min:
A    1
B    4
C    7
dtype: int64
Answer

import
pandas
as
pd
data
=
{
'A'
: [
1
,
2
,
3
],
'B'
: [
4
,
5
,
6
],
'C'
: [
7
,
8
,
9
]
}
df
=
pd
.
DataFrame
(
data
)
print
(
"Operations on rows:"
)
print
(
"Count:"
)
print
(
df
.
count
(
axis
=
1
))
print
(
"Sum:"
)
print
(
df
.
sum
(
axis
=
1
))
print
(
"Max:"
)
print
(
df
.
max
(
axis
=
1
))
print
(
"Min:"
)
print
(
df
.
min
(
axis
=
1
))
print
(
"
\n
Operations on columns:"
)
print
(
"Count:"
)
print
(
df
.
count
())
print
(
"Sum:"
)
print
(
df
.
sum
())
print
(
"Max:"
)
print
(
df
.
max
())
print
(
"Min:"
)
print
(
df
.
min
())
Output
Operations on rows:
Count:
0 3
1 3
2 3
dtype: int64
Sum:
0 12
1 15
2 18
dtype: int64
Max:
0 7
1 8
2 9
dtype: int64
Min:
0 1
1 2
2 3
dtype: int64

Operations on columns:
Count:
A 3
B 3
C 3
dtype: int64
Sum:
A 6
B 15
C 24
dtype: int64
Max:
A 3
B 6
C 9
dtype: int64
Min:
A 1
B 4
C 7
dtype: int64