在pandas read_csv中,有没有办法指定例如。 col1、col15、整行?
我正在尝试从一个文本文件导入大约 700000 行数据,该文件以帽子“^”作为分隔符,没有文本限定符,并以回车符作为行分隔符。
在文本文件中,我需要第 1 列、第 15 列,然后是表/数据帧的三列中的整行。
我已经搜索过如何在 pandas 中执行此操作,但不太了解它以获取逻辑。我可以很好地导入所有 26 列,但这对我的问题没有帮助。
my_df = pd.read_csv("tablefile.txt", sep="^", lineterminator="\r", low_memory=False)
或者我可以使用标准 python 将数据放入表中,但这需要大约 4 小时才能处理 700000 行。这对我来说太长了。
count_1 = 0
for line in open('tablefile.txt'):
if count_1 > 70:
break
else:
col1id = re.findall('^(\d+)\^', line)
col15id = re.findall('^.*\^.*\^(\d+)\^.*\^.*\^.*\^.*\^.*\^.*\^.*\^.*\^.*\^.*\^.*', line)
line = line.strip()
count_1 = count_1 + 1
cur.execute('''INSERT INTO mytable (mycol1id, mycol15id, wholeline) VALUES (?, ?, ?)''',
(col1id[0], col15id[0], line, ) )
conn.commit()
print('row count_1=',count_1)
在pandas read_csv中,有没有办法指定例如。 col1、col15、整行?
如上,col1
和col15
是数字,wholeline
是字符串
- 我不想在导入后重建字符串,因为我可能会在此过程中丢失一些字符。
谢谢
编辑: 将每一行提交到数据库非常耗时。
最佳答案
使用一些准分隔符(下面使用 &)将整行作为一个 df 读取,然后使用 usecols 再次读取并指定第 1 列和第 15 列的索引,并将它们添加在一起。
my_df_full = pd.read_csv("tablefile.txt", sep="&", lineterminator="\r", low_memory=False)
my_df_full.columns = ['full_line']
my_df_cols = pd.read_csv("tablefile.txt", sep="^", lineterminator="\r", low_memory=False, usecols=[1,15])
my_df_full[['col1', 'col15']] = my_df_cols
关于python - pandas dataframe read_csv,指定列并将整行保留为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42134428/