如何切片 pandas 数据帧(获取子集)?
How to slice a pandas dataframe (get a subset)?
如何在特定的 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]]))
如何在特定的 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]]))