如何将数据帧切片为特定x,y位置的子集数据帧?
。如何获得左上,右上,左下,右下和中间的2x2区域作为子集数据框?
df = pd.DataFrame([
[16, 3, 2, 13],
[5, 10, 11, 8],
[9, 6, 7, 12],
[4, 15, 14, 1]
])
预期:
# top-left 2x2
[
[16, 3],
[5, 10]
]
# center 2x2
[
[10, 11],
[16, 17]
]
# etc for top-right, bottom-left, bottom-right.
可以使用底层numpy数组(也可以使用pandas和iloc
,但为什么要让事情变得更复杂呢?)
a = df.values
x,y = a.shape
X,Y = x//2,y//2
a[:2,:2],a[-2:,:2],a[:2,-2:],a[-2:,-2:],a[X-1:X+1, Y-1:Y+1]
输出:
(array([[16, 3],
[ 5, 10]]),
array([[ 9, 6],
[ 4, 15]]),
array([[ 2, 13],
[11, 8]]),
array([[ 7, 12],
[14, 1]]),
array([[10, 11],
[ 6, 7]]))