我有数据帧(63 cols x 7446行)。 我要做的是对数据帧进行切片,以使用.iloc()
生成由特定列组成的新数据帧,这些列由它们的位置指定。
我编写了以下代码,但它不起作用,我得到以下错误:
TypeError: cannot do slice indexing on <class 'pandas.core.indexes.base.Index'> with these indexers [12] of <class 'int'>
基本上,我希望函数拆分数据框架,将它们保存为新变量,然后用.to_csv()
将它们保存为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
。
让我知道如果这是有意义的,并预先感谢帮助!
注意:我没有包含数据框架的片段,因为它太大了,但是如果有必要,请告诉我,这样您就可以有一个工作示例了。
编辑:在用loc
和iloc
修复了愚蠢的错误之后,我现在得到以下错误:
IndexError: list index out of range
看起来您使用的是.loc
属性,但使用的是整数范围切片器:
pd.concat([df.iloc[:,0:3], df.loc[:,nums[j]:nums[j]+3]], axis=1)
# HERE ^
您可能还打算使用.iloc
。
问题似乎是使用.loc
而不是.iloc
。
尝试替换:
locals()["split"+str(i)] = pd.concat([df.iloc[:,0:3],df.loc[:,nums[j]:nums[j]+3]], axis=1)
用这个:
locals()["split"+str(i)] = pd.concat([df.iloc[:,0:3],df.iloc[:,j:j+3]], axis=1)
如果列按顺序排列,则可以使用下面的方法
split1 = df.iloc[:, 0:6]
split2 = df.iloc[:, 0:18]
如果列不按顺序排列,则可以使用以下方式
split1 = df[['col1', 'col2']]
split2 = df[['col0', 'col4']]