Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 读取固定宽度的文本文件,其中包含pandas中的varchar_Python_Pandas_Csv_Varchar_Fixed Width - Fatal编程技术网

Python 读取固定宽度的文本文件,其中包含pandas中的varchar

Python 读取固定宽度的文本文件,其中包含pandas中的varchar,python,pandas,csv,varchar,fixed-width,Python,Pandas,Csv,Varchar,Fixed Width,我想读入一个固定宽度格式的文本文件。不幸的是,它还包含一个varchar字段,它告诉我开始时的长度,所以宽度毕竟不是固定的。 文件看起来像这样 Boris 1520190730 0014likes icecreamblue Lena 1320190815 0009is blondered 使用类似以下内容的模式: { 'name':10, 'age':2, 'last_visit':8, 'other_field':5, 'comment':???, 'fav

我想读入一个固定宽度格式的文本文件。不幸的是,它还包含一个varchar字段,它告诉我开始时的长度,所以宽度毕竟不是固定的。 文件看起来像这样

Boris     1520190730     0014likes icecreamblue
Lena      1320190815     0009is blondered
使用类似以下内容的模式:

{
'name':10,
'age':2,
'last_visit':8,
'other_field':5,
'comment':???,
'fav_color':8
}
在我遇到varchar字段之前,我的方法是使用pandas的read_fwf或通过df[col].str[schema[col][0]:schema[col][1]稍微修改的模式来读取它。对于可变长度字段,这当然是失败的。至少字段在0014和0009开头告诉我它的长度

有没有办法读入这样的文件?或者我必须逐行循环并动态处理字段?

您可以使用正则表达式分隔符和转换器读取数据,然后进行一些后处理,例如:

import pandas

schema = {
    'name': 10,
    'age': 2,
    'last_visit': 8,
    'other_field': 5,
    'comment': None,
    'fav_color': 8
}


# A converter for the variable length and following columns
def converter(x):
    """Return the comment and the fav_color values separated by ','."""
    length_len = 4
    comment_len = int(x[:length_len])
    return x[length_len:comment_len + length_len:] + ',' + x[comment_len + length_len:]


# A regex as delimiter for the fixed length columns
delimiter = f"(.{{{schema['name']}}})(.{{{schema['age']}}})(.{{{schema['last_visit']}}}).{{{schema['other_field']}}}(.*)"
# Use the delimiter and converter (column 4 holds comment and fav_color) for reading the table
data = pandas.read_table('input.txt', header=None, sep=delimiter, converters={4: converter})
# Clean the table
data.dropna(inplace=True, axis=1)
# Split the comment and the fav_color columns
data[5], data[6] = data[4].str.split(',', 1).str