0

I am brand new to Pandas and following along with a Plurasight course I have gotten stuck on how can I rewrite the following to use loc instead of chained indexing.

every_6th_row = pd.Series(range(5, len(df),6))

# can you rewrite this line to use df.loc
df['MIN_TEMP_GROUND'].drop(every_6th_row).isnull().all()

Within the dataframe there is only a value in the column MIN_TEMP_GROUND every six rows, so this statement checks to ensure that all the other rows are null.

I have tried a number of combinations such as:

df.drop(df.loc[every_6th_row, 'MIN_TEMP_GROUND'])

without success. Any pointers to where I am going wrong would be appreciated.

1 Answer 1

1

Assuming a 0 indexed DataFrame, let's try using the modulus of the index and keep all rows except the 6th:

df.loc[(df.index % 6) != 5, 'MIN_TEMP_GROUND'].isnull().all()  # True

Or more generally based on the shape of the DataFrame and arange if the index is not a 0 indexed range already:

df.loc[(np.arange(df.shape[0]) % 6) != 5, 'MIN_TEMP_GROUND'].isnull().all()

Sample Data:

import numpy as np
import pandas as pd

df = pd.DataFrame({'MIN_TEMP_GROUND': [np.nan, np.nan, np.nan,
                                       np.nan, np.nan, 5] * 2})
    MIN_TEMP_GROUND
0               NaN
1               NaN
2               NaN
3               NaN
4               NaN
5               5.0
6               NaN
7               NaN
8               NaN
9               NaN
10              NaN
11              5.0
df.loc[(df.index % 6) != 5, 'MIN_TEMP_GROUND']
0    NaN
1    NaN
2    NaN
3    NaN
4    NaN
6    NaN
7    NaN
8    NaN
9    NaN
10   NaN
Name: MIN_TEMP_GROUND, dtype: float64
1
  • 1
    Perfect - First answer fits the spec because the course hasn't yet touched on shape Jul 1, 2021 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.