Home > Blockchain >  How to create a new dataframe by looping until a certain criteria is met
How to create a new dataframe by looping until a certain criteria is met

Time:12-07

Here is a dataframe

dataframe = {'Mon':[1,7,0,4,2,8],
             'Tue':[8,4,2,5,9,3],
             'Wed':[0,5,1,1,4,3],
             'Thu':[8,6,5,7,6,8],
             'Fri':[4,5,4,6,5,7],
             'index':['Lucy','Guzy','Lisa,'Kala','Lura','kim']}

That looks like:

index Mon Tue Wed Thu Fri
lucy  1   8   0   8   4
Guzy  7   4   5   6   5
Lisa  0   2   1   5   4
Kala  4   5   1   7   6
lura  2   9   4   6   5
kimi  8   3   3   8   7

I would like to use a loop to iterate over this dataframe selecting every nth row to create a new dataframe until the new dataframe has a length of 6.

This is what i've attempted but not sure how to proceed: In this case n = 3

row = 0
for row in len(dataframe):
    row = row   3
    if row 

I don't care about efficiency and would like to use a loop to do this.

CodePudding user response:

First slice every three rows with iloc[::3], then use iterrows to loop over them:

for idx,row in dataframe.iloc[::3].iterrows():
    print(f'row {idx}')
    print(row)

Output:

row 0
Mon         1
Tue         8
Wed         0
Thu         8
Fri         4
index    Lucy
Name: 0, dtype: object
row 3
Mon         4
Tue         5
Wed         1
Thu         7
Fri         6
index    Kala
Name: 3, dtype: object
  • Related