0

Say, I have a Pandas DataFrame with 3 columns and rows 0,1,2 ... 1000. Then, suppose I extract a DataFrame from this such that it has randomly selected rows 1,5,9... 999.

Now, how can I iterate over the rows of this new DataFrame with alternating odd rows? A for-loop iterating from 0 through 1000 would return KeyError at inappropriate indices in the new DataFrame, for example. Is there a way to get a list of the rows that are retained in the new DateFrame?

P.S. I lack experience with this website, so apologies if my question could've been formatted better. Thank you.

algebroo
  • 132
  • 6

1 Answers1

0

Try filtering with isin and accessing index of the new dataframe.

import pandas as pd
import numpy as np

col1 = np.random.randint(0, 10, 10)
col2 = np.random.randint(10, 100, 10)
col3 = np.random.randint(200, 300, 10)
df = pd.DataFrame({'col1': col1, 'col2': col2, 'col3': col3})
     col1  col2  col3
# 0     2    90   262
# 1     8    36   258
# 2     9    45   278
# 3     1    43   269
# 4     8    72   206
# 5     6    55   211
# 6     9    60   259
# 7     6    39   259
# 8     6    57   214
# 9     0    35   280

sequence = [1, -2, 3, -4, 5, -6, 7, -8, 9, -10]
filtered_df = df[df.index.isin(sequence)]
print(filtered_df.index)
# Int64Index([1, 3, 5, 7, 9], dtype='int64')
Czysztof
  • 51
  • 3