KnowledgeBoat Logo
|

Informatics Practices

Create a dataframe of [23, 25], [34], [43, 44, 45, 46] and do the following: :

(a) Display the dataframe. Notice that the missing value is represented by NaN.

(b) Replace the missing value with 0.

(c) Replace the missing value with -1, -2, -3, -4 for columns 0, 1, 2, 3.

(d) Replace the missing value by copying the value from the above cell.

Python Data Handling

1 Like

Answer

(a)

import pandas as pd

data = [[23, 25], 
        [34], 
        [43, 44, 45, 46]]
df = pd.DataFrame(data)
print(df)
Output
    0     1     2     3
0  23  25.0   NaN   NaN
1  34   NaN   NaN   NaN
2  43  44.0  45.0  46.0

(b)

df = df.fillna(0)
Output
    0     1     2     3
0  23  25.0   0.0   0.0
1  34   0.0   0.0   0.0
2  43  44.0  45.0  46.0

(c)

df = df.fillna({0:-1, 1:-2, 2:-3, 3:-4})
Output
    0     1     2     3
0  23  25.0  -3.0  -4.0
1  34  -2.0  -3.0  -4.0
2  43  44.0  45.0  46.0

(d)

df= df.fillna(method='ffill')
Output
    0     1     2     3
0  23  25.0   NaN   NaN
1  34  25.0   NaN   NaN
2  43  44.0  45.0  46.0

Answered By

3 Likes


Related Questions