首页 > 解决方案 > 如何提取熊猫数据框的一部分,如下图所示?

问题描述

单击此处打开标记的图像

我正在尝试提取熊猫数据框中数字的部分(矩阵),如上面嵌入的给定图片中标记的那样。
请任何可以帮助我的人,我想根据更大数据框的部分(矩阵)执行分析。先感谢您!!

标签: pythonpandas

解决方案


您可以使用 .iloc[] 函数来选择所需的行和列。

dataframe.iloc[5:15,6:15]

这应该选择第 5-14 行和第 6-14 列。不确定数字是否正确,但我认为这种方法是您正在寻找的。

编辑:将 .loc[] 更改为 .iloc[] 因为我们正在使用索引值,并对其进行了一些清理

这是遍历整个数据框的代码

#df = big data frame
shape = (10,10) #shape of matrix to be analized, here is 10x10
step = 1 #step size, itterate over every number
        #or
step = 10 #step size, itterate block by block
        #keep in mind, iterating by block will leave some data out at the end of the rows and columns
#you can set step = shape if you are working  with a matrix that isn't square, just be sure to change step in the code below to step[0] and step[1] respectively 
for row in range( 0, len(df[0]) - shape[0]+1, step): #number of rows of big dataframe - number of rows of matrix to be analized 
   for col in range(0, len(df.iloc[0,:]) - shape[1]+1, step): #number of columns of big dataframe - number of columns of matrix to be analized 
        matrix = df.iloc[row:shape[0]+row, col:shape[1]+col] #slice out matrix and set it equal to 'matrix'
        #analize matrix here
    

这与@dafmedinama 所说的基本相同,我只是添加了更多评论并简化了指定矩阵的形状,并且如果您不想在每次移动矩阵时都迭代每个数字,还包括一个 step 变量。


推荐阅读