logo_learn_stats

Pandas: Tips on how to Reset Index Then The use of dropna()

Posted on
banner 336x280

You’ll significance please see ordinary syntax to reset an index of a pandas DataFrame upcoming the usage of the dropna() serve as to take away rows with lacking values:

df = df.dropna().reset_index(shed=True)

Please see instance presentations how you can significance this syntax in follow.

banner 468x60

Instance: Reset Index in Pandas Then The use of dropna()

Assume now we have please see pandas DataFrame that accommodates details about diverse basketball avid gamers:

import pandas as pd
import numpy as np

#manufacture dataFrame
df = pd.DataFrame({'workforce': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   'issues': [18, np.nan, 19, 14, 14, 11, 20, 28],
                   'assists': [5, 7, 7, 9, 12, np.nan, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, np.nan, 12]})

#view DataFrame
print(df)

  workforce  issues  assists  rebounds
0    A    18.0      5.0      11.0
1    B     NaN      7.0       8.0
2    C    19.0      7.0      10.0
3    D    14.0      9.0       6.0
4    E    14.0     12.0       6.0
5    F    11.0      NaN       5.0
6    G    20.0      9.0       NaN
7    H    28.0      4.0      12.0

Now assume we significance the dropna() serve as to shed all rows from the DataFrame that experience a lacking price in any column:

#shed rows with nan values in any column
df = df.dropna()

#view up to date DataFrame
print(df)

  workforce  issues  assists  rebounds
0    A    18.0      5.0      11.0
2    C    19.0      7.0      10.0
3    D    14.0      9.0       6.0
4    E    14.0     12.0       6.0
7    H    28.0      4.0      12.0

Realize that the index nonetheless accommodates the actual index values for each and every row.

To reset the index upcoming the usage of the dropna() serve as, we will significance please see syntax:

#shed rows with nan values in any column
df = df.dropna().reset_index(shed=True)

#view up to date DataFrame
print(df)

  workforce  issues  assists  rebounds
0    A    18.0      5.0      11.0
1    C    19.0      7.0      10.0
2    D    14.0      9.0       6.0
3    E    14.0     12.0       6.0
4    H    28.0      4.0      12.0

Realize that each and every of the rows with lacking values were got rid of and the index values were reset.

The index values now dimension from 0 to 4.

Supplementary Sources

Please see tutorials provide an explanation for how you can carry out alternative habitual duties in pandas:

Tips on how to Print Pandas DataFrame with Negative Index
Tips on how to Filter out by means of Index Price in Pandas
Tips on how to Usefulness First Column as Index in Pandas

banner 336x280

Leave a Reply

Your email address will not be published. Required fields are marked *