jezrael jezrael - 5 months ago 16
Python Question

Split odd rows of DataFrame without double iloc

Test

df
:

import pandas as pd

df = pd.DataFrame({'A':[1,2,3,7,8,4],
'B':[4,5,6,1,4,6],
'C':[7,8,9,2,7,3],
'D':[4,5,2,1,0,6]})

df.set_index(['A','B'], inplace=True)
print (df)
C D
A B
1 4 7 4
2 5 8 5
3 6 9 2
7 1 2 1
8 4 7 0
4 6 3 6


Splitted by odd rows:

print (df.iloc[::2])
C D
A B
1 4 7 4
3 6 9 2
8 4 7 0


I need split it again - last row in
df1
and all other rows to
df2
:

df1 = df.iloc[-2::2]
df2 = df.iloc[::2].iloc[:-1,:]

print (df1)
C D
A B
8 4 7 0

print (df2)
C D
A B
1 4 7 4
3 6 9 2


Is better solution without double
iloc
?

Answer

Wouldn't this work?

df2 = df.iloc[:-2:2]

     C  D
A B      
1 4  7  4
3 6  9  2
Comments