Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What's the [0] at the end is for?

Currently I’m learning and working with pandas DataFrame and had to solve a problem where I need to fill the NaN values with mode with respective series, this is working but I can’t figure out what’s the [0] at the end is for. Also is it possible to perform same on the whole DataFrame in one go?

df[‘col1’] = df[‘col1’].fillna(df[‘col1’].mode()[0])

import pandas as pd
import numpy as np
data = {'birds': ['Cranes', 'Cranes', 'plovers', 'spoonbills', 'spoonbills', 'Cranes', 'plovers', 'Cranes', 'spoonbills', 'spoonbills', 'Cranes'], 
        'age': [3.5, 4, 1.5, np.nan, 6, 3, 5.5, np.nan, 8, 4, 3.5], 'visits': [2, 4, 3, 4, 3, 4, 2, 2, 3, 2, 2], 
        'priority': ['yes', 'yes', 'no', np.nan, 'no', 'no', 'no', 'yes', 'no', 'no','yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']
df = pd.DataFrame(data)
df.rename(index = {0:'a', 1:'b', 2:'c', 3:'d', 4:'e', 5:'f', 6:'g', 7:'h', 8:'i', 9:'j', 10:'k'})
df.iloc[::2]

**df['age'] = df['age'].fillna(df['age'].mode()[0])
df**

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

mode() returns a Series (a type of pandas DataFrame), not a single value. This is because there can technically be multiple modes in a dataset. By indexing with [0], you are selecting the first mode in the dataset.

Also, for doing this for the whole dataset you can use:

df = df.apply(lambda x: x.fillna(x.mode()[0]) if x.dtype.name == 'object' else x)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading