首页 > 解决方案 > 使用for循环拆分数据帧的功能

问题描述

我有数据框(63 cols x 7446 行)。我想要做的是切片数据帧以制作新的数据帧,这些数据帧由其位置指定的特定列组成,使用.iloc().

我已经编写了以下代码,但它不起作用,我收到此错误:

TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [12] of <class 'int'>

基本上我希望函数拆分数据框,将它们保存为新变量,然后将它们保存为 csv 文件.to_csv()。我还没有完成保存数据帧的那部分工作,但是对此的任何输入将不胜感激。

这是我的代码:

names = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
nums = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60]

#Function to split df into the 20 joints and save them as csv
def splitAndSave(df):
    for i in names:
        for j in nums:
            #selects columns to be put into a new dataframe, concatenating them if they are not adjacent
            locals()["split"+str(i)] = pd.concat([df.iloc[:,0:3],df.iloc[:,nums[j]:nums[j]+3]], axis=1)

    #save outputs as csv?

所需的输出将是具有多个变量,如下所示:
split1是具有以下列的数据框:col0, col1, col2, col3, col4, col5
然后
split2是具有以下列的数据框:col0, col1, col2, col6, col7, col8
等,一直到split20.

让我知道这是否有意义,并提前感谢您的帮助!

注意:我没有包含数据框的片段,因为它太大了,但如果有必要请告诉我,以便您可以有一个工作示例。

编辑:修复愚蠢的错误后lociloc我现在收到以下错误:

IndexError: list index out of range

更新:根据答案和更多研究对代码进行了一些更改,我现在有了这个:

d = {}
#Function to split df into the 20 joints and save them as csv

    def splitAndSave(df):
        for i in names:
            for j in nums:
                #selects columns to be put into a new dataframe, concatenating them if they are not adjacent
                d["split{0}".format(i)] = pd.concat([df.iloc[:,0:3],df.iloc[:,j:j+3]], axis=1)
        return d

现在的问题是,虽然它动态更新变量名(split1, 2等),但它对j. 我得到的输出是

{'split1':       col0   col1        col2  col61  col62  col63
'split2':       col0   col1        col2  col61  col62  col63 ... }

为什么它不循环nums更新j,为什么只选择最后三列?

DATA:这是数据帧的片段,它由 63 列组成,下面的前 3 列(Frame、Time、SMPTE)然后其他 60 列与 类似bar_head_x/y/z,只是名称不同。我只包含了这六列作为数据框的概念:

  Frame Time    SMPTE       bar_head_x  bar_head_y  bar_head_z
0   1   0.00    02:45:25:03 -203.3502   1554.3486   1102.8210
1   2   0.01    02:45:25:03 -203.4280   1554.3492   1103.0592
2   3   0.02    02:45:25:03 -203.4954   1554.3234   1103.2794
3   4   0.03    02:45:25:04 -203.5022   1554.2974   1103.4522
4   5   0.04    02:45:25:04 -203.5014   1554.2948   1103.6594

目前每个 split_i 的输出基本相同(参见上面的更新)。所需的输出是:

{'split1':       col0   col1   col2  col3  col4  col5
 'split2':       col0   col1   col2  col6  col7  col8
 'split3':       col0   col1   col2  col9  col10  col11 ... }

显然,每一列都包含来自原始数据帧的相应数据。

标签: pythonpandasdataframefor-loop

解决方案


看起来您正在使用该.loc属性,但使用的是整数范围切片器:

pd.concat([df.iloc[:,0:3], df.loc[:,nums[j]:nums[j]+3]], axis=1)
#                         HERE ^

您可能也打算.iloc在那里使用。


推荐阅读