gpt4 book ai didi

python - 如何在 pandas 中使用 read_fwf 跳过空行?

转载 作者:太空宇宙 更新时间:2023-11-03 11:44:35 25 4
gpt4 key购买 nike

我在 Python pandas 0.19.2 中使用 pandas.read_fwf() 函数读取具有以下内容的文件 fwf.txt:

# Column1 Column2
123 abc

456 def

#
#

我的代码如下:

import pandas as pd
file_path = "fwf.txt"
widths = [len("# Column1"), len(" Column2")]
names = ["Column1", "Column2"]
data = pd.read_fwf(filepath_or_buffer=file_path, widths=widths,
names=names, skip_blank_lines=True, comment="#")

打印出来的dataframe是这样的:

    Column1 Column2
0 123.0 abc
1 NaN NaN
2 456.0 def
3 NaN NaN

看起来 skip_blank_lines=True 参数被忽略了,因为数据帧包含 NaN。

确保跳过空行的 pandas.read_fwf() 参数的有效组合应该是什么?

最佳答案

import io
import pandas as pd
file_path = "fwf.txt"
widths = [len("# Column1 "), len("Column2")]
names = ["Column1", "Column2"]

class FileLike(io.TextIOBase):
def __init__(self, iterable):
self.iterable = iterable
def readline(self):
return next(self.iterable)

with open(file_path, 'r') as f:
lines = (line for line in f if line.strip())
data = pd.read_fwf(FileLike(lines), widths=widths, names=names,
comment='#')
print(data)

打印

   Column1 Column2
0 123 abc
1 456 def

with open(file_path, 'r') as f:
lines = (line for line in f if line.strip())

定义生成器表达式(即可迭代对象),它产生文件中删除了空行的行。

pd.read_fwf 函数可以接受TextIOBase 对象。你可以继承TextIOBase 以便其 readline 方法从可迭代对象返回行:

class FileLike(io.TextIOBase):
def __init__(self, iterable):
self.iterable = iterable
def readline(self):
return next(self.iterable)

把这两个放在一起给你一种操作/修改文件行的方法在将它们传递给 pd.read_fwf 之前。

关于python - 如何在 pandas 中使用 read_fwf 跳过空行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42582838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com