pandas.read_fwf(filepath_or_buffer, colspecs='infer', widths=None, infer_nrows=100, **kwds)源代码
将具有固定宽度格式的行组成的表读入DataFrame。
还支持可选的文件迭代或分割成块。
可以在online docs for IO Tools中找到其他帮助
参数:filepath_or_buffer: str,path对象或类文件对象
任何有效的字符串路径都是可接字符串可以是URL。
有效的URL方案包括http,ftp,s3和file。对于文件URL,
需要主机。本地文件可以是:file://localhost/path/to/table.csv。
如果要传入路径对象,
pandas接受pathlib.Path或py._path.local.LocalPath。
通过类似文件的对象,我们使用read()方法引用对象,
例如,文件处理程序(例如,通过内置的open函数)或StringIO。
colspecs: 元组(int,int)或‘infer’的列表。可选的
一个元组列表,给出每行固定宽度字段的范围为半开间隔(即[from,to [)。
字符串值'infer'可用于指示解析器尝试从未通过skiprows(default ='infer')
跳过的数据的前100行检测列规范。
widths : int列表,可选
如果间隔是连续的,则可以使用字段宽度列表(list)代替'colspecs'。
infer_nrows:int,默认为100
让解析器确定colspecs时要考虑的行数。
版本0.24.0中的新功能。
**kwds: 可选
可选的关键字参数可以传递给TextFileReader。
返回:DataFrame或TextParser
逗号分隔值(csv)文件作为具有标记轴的二维数据结构返回。
例子,col_names = ['line_name', 'year', 'day', 'hour', 'minute', 'second',
'sensor', 'spring_tension', 'cross_coupling',
'raw_beam', 'vcc', 'al', 'ax', 've2', 'ax2', 'xacc2',
'lacc2', 'xacc', 'lacc', 'par_port', 'platform_period']
col_widths = [10, 4, 3, 2, 2, 2, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 6]
time_columns = ['year', 'day', 'hour', 'minute', 'second']
# read into dataframe
df = pd.read_fwf('data.csv', widths=col_widths, names=col_names)
day_fmt = lambda x: '{:03d}'.format(x)
time_fmt = lambda x: '{:02d}'.format(x)
t = df['year'].map(str) + df['day'].map(day_fmt) + \
df['hour'].map(time_fmt) + df['minute'].map(time_fmt) + \
df['second'].map(time_fmt)
# index by datetime
df.index = pd.to_datetime(t, format='%Y%j%H%M%S')
df.drop(time_columns, axis=1, inplace=True)