测试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
按奇数行拆分:
print (df.iloc[::2])
C D
A B
1 4 7 4
3 6 9 2
8 4 7 0
我需要再次拆分-df1的最后一行,所有其他行到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
解决方法:
这行不行吗?
df2 = df.iloc[:-2:2]
C D
A B
1 4 7 4
3 6 9 2