一种高效、畅销的方法,可以遍历一个数据帧,并逐行写入文本文件,其中包含大量的文本数据

2024-03-29 11:23:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个大的数据帧,其中每一行都包含大量的文本数据,我试图在数据帧的某一列(即第11列)上对该数据帧进行分区,然后写入多个文件

partitioncount = 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]) + "\n")

此代码导致错误: 索引器错误回溯(最近一次调用) 在() --->;73个输出文件[partition].write(“\t”.join([str(num)代表num in测向仪[索引].values])+“\n”)

c:\python27\lib\site packages\pandas\core\索引.pyc在getitem中(self,key) 1326其他: 1327 key=com.如果可调用,则应用(key,自我.obj) ->;1328返回self.\u getitem_axis(键,轴=0) 1329 1330 def\u是标量访问(self,key):

c:\python27\lib\site packages\pandas\core\索引.pyc在轴中(self、key、axis) 1747 1748#验证位置 ->;1749 self.\u是有效的整数(键,轴) 1750 1751返回self.\u get_loc(键,轴=轴)

c:\python27\lib\site packages\pandas\core\索引.pyc整数(u轴,u是有效的) 1636 l=长度(ax) 1637如果key>;=l或key<;-l: ->;1638 raise IndexError(“单个位置索引器越界”) 1639返回True 1640年

索引器错误:单个位置索引器超出范围

最有效和可伸缩的方法是什么,即迭代数据帧的行,对行执行一些操作(我在上面的代码中没有显示这些操作,与手头的问题无关),最后将每一行(包含大量文本数据)写入文本文件。

谢谢你的帮助!在


Tags: 数据keyingtselfdfforlib
1条回答
网友
1楼 · 发布于 2024-03-29 11:23:09

你可以这样做:

filename = 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))

相关问题 更多 >