Informatics Practices
Given a dataframe df as shown below :
| A | B | D | |
|---|---|---|---|
| 0 | 15 | 17 | 19 |
| 1 | 16 | 18 | 20 |
| 2 | 20 | 21 | 22 |
What will be the result of following code statements ?
(a) df['C'] = np.NaN
(b) df['C'] = [2, 5]
(c) df['C'] = [12, 15, 27]
Answer
(a) df['C'] = np.NaN — This statement will add a new column 'C' to the dataframe and assign np.NaN (Not a Number) to all rows in this new column.
The updated dataframe will look like this:
Output
A B D C
0 15 17 19 NaN
1 16 18 20 NaN
2 20 21 22 NaN
(b) df['C'] = [2, 5] — This statement will result in error because the length of the list [2, 5] does not match the number of rows in the DataFrame df.
(c) df['C'] = [12, 15, 27] — This statement will add a new column 'C' to the dataframe and assign the values from the list [12, 15, 27] to the new column. This time, all rows in the new column will be assigned a value.
The updated dataframe will look like this:
Output
A B D C
0 15 17 19 12
1 16 18 20 15
2 20 21 22 27
Related Questions
Given the following Series S1 and S2 :
S1 A 10 B 40 C 34 D 60 S2 A 80 B 20 C 74 D 90 Write the command to find the sum of series S1 and S2.
Consider two objects x and y. x is a list whereas y is a Series. Both have values 20, 40, 90, 110.
What will be the output of the following two statements considering that the above objects have been created already ?
(a) print (x*2)
(b) print (y*2)
Justify your answer.
Write code statements to list the following, from a dataframe namely sales:
(a) List only columns 'Item' and 'Revenue'.
(b) List rows from 3 to 7.
(c) List the value of cell in 5th row, 'Item' column.
Hitesh wants to display the last four rows of the dataframe df and has written the following code :
df.tail()But last 5 rows are being displayed. Identify the error and rewrite the correct code so that last 4 rows get displayed.