我有一个很大的数据框,其中每一行都包含大量文本数据,我试图将此数据框分区到我的数据框的某个列上,即第11列,然后写入多个文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15partitioncount = 5
trainingDataFile = 'sometrainingDatFileWithHugeTextDataInEachColumn.tsv'
df = pd.read_table(trainingDataFile, sep='\t', header=None, encoding='utf-8')
# prepare output files and keep them to append the dataframe rows
outputfiles = {}
filename ="C:\Input_Partition"
for i in range(partitioncount):
outputfiles[i] = open(filename +"_%s.tsv"%(i,),"a")
#Loop through the dataframe and write to buckets/files
for index, row in df.iterrows():
#partition on a hash function
partition = hash(row[11]) % partitioncount
outputfiles[partition].write("\t".join([str(num) for num in df.iloc[index].values]) +"
")
此代码导致错误:
IndexError Traceback(最近一次通话)
在()中
---> 73个outputfiles [partition] .write(" t" .join([df.iloc [index] .values]中num的[str(num))+" n")
在getitem中的c: python27 lib site-packages pandas core indexing.pyc(self,key)
1326其他:
1327 key = com._apply_if_callable(key,self.obj)
-> 1328返回self._getitem_axis(key,axis = 0)
1329
1330 def _is_scalar_access(self,key):
_getitem_axis(self,key,axis)中的c: python27 lib site-packages pandas core indexing.pyc
1747
1748#验证位置
-> 1749 self._is_valid_integer(键,轴)
1750
1751 return self._get_loc(key,axis = axis)
_is_valid_integer中的c: python27 lib site-packages pandas core indexing.pyc(自,键,轴)
1636升= len(ax)
1637如果键> = l或键 1638提高IndexError("单个位置索引器超出范围")
1639返回True
1640
IndexError:单个位置索引器超出范围
什么是最有效,最可扩展的方法,即迭代数据帧的行,对行进行一些操作(我在上面的代码中没有显示并且与手头的问题无关)并最终写入每行(包含大量文本)数据)转换为文本文件。
感谢任何帮助!
partition = hash(row[11]) % partitioncount让我有些困惑。 这应该怎么办?
它只是一个散列函数,用于随机选择存储桶/文件。 它从第11列获取值,对其进行哈希处理(以进行随机化),然后应用模5,这将使您最多获得5个分区。
IIUC您可以通过以下方式进行操作:
1
2
3
4filename = r'/path/to/output_{}.csv'
df.groupby(df.iloc[:, 11].map(hash) % partitioncount) \
.apply(lambda g: g.to_csv(filename.format(g.name), sep='\t', index=False))
这很酷,我学到了一些新东西,但是,我必须创建一致的partitions,这意味着我需要限制每个组的示例数。 即每个组每个分区的示例数不能超过1k。 使用此解决方案,组的所有示例都将进入一个分区/文件。