Python Pandas read_csv 到没有分隔符的数据框

标签 python pandas

我是 Pandas 库的新手。
我共享了基于数据框的代码。

有没有办法在没有任何定界符的情况下逐行读取 gzip 文件(使用整行,该行可以包含逗号和其他字符)作为单行并在数据框中使用它?似乎你必须提供一个分隔符,当我提供“\n”时它能够读取但 error_bad_lines 会提示“跳过行 xxx:预期 22 个字段但得到 23 个”字段,因为每一行都不同。

我希望它将每一行视为数据框中的一行。如何实现?任何提示将不胜感激。

最佳答案

如果您只想让每一行成为一行和一列,那么请不要使用 read_csv。只需逐行读取文件并从中构建数据框。

您可以通过创建一个带有单个列标题的空数据框来手动执行此操作。然后遍历文件中的每一行,将其附加到数据框。

#explicitly iterate over each line in the file appending it to the df.
import pandas as pd
with open("query4.txt") as myfile:
    df = pd.DataFrame([], columns=['line'])
    for line in myfile:
        df = df.append({'line': line}, ignore_index=True)
    print(df)

这适用于大文件,因为我们一次只处理一行并构建数据框,因此我们不会使用超过需要的内存。这可能不是最有效的,这里有很多数据帧的重新分配,但它肯定会起作用。

但是我们可以更干净地做到这一点,因为 pandas 数据框可以将可迭代对象作为数据输入。

#create a list to feed the data to the dataframe.
import pandas as pd
with open("query4.txt") as myfile:
    mydata = [line for line in myfile]
    df = pd.DataFrame(mydata, columns=['line'])
    print(df)

这里我们将文件的所有行读取到一个列表中,然后将该列表传递给 pandas 以从中创建数据。然而,不利的一面是,如果我们的文件非常大,我们基本上会在内存中拥有它的 2 个副本。一个在列表中,一个在数据框中。

鉴于我们知道 pandas 将接受数据的可迭代对象,因此我们可以使用生成器表达式为我们提供一个生成器,该生成器会将文件的每一行提供给数据框。现在,数据框将通过从文件中一次读取每一行来自行构建。

#create a generator to feed the data to the dataframe.
import pandas as pd
with open("query4.txt") as myfile:
    mydata = (line for line in myfile)
    df = pd.DataFrame(mydata, columns=['line'])
    print(df)

在这三种情况下都不需要使用 read_csv,因为您要加载的数据不是 csv。每个解决方案都提供相同的数据帧输出

源数据

this is some data
this is other data
data is fun
data is weird
this is the 5th line

数据框

                   line
0   this is some data\n
1  this is other data\n
2         data is fun\n
3       data is weird\n
4  this is the 5th line

关于Python Pandas read_csv 到没有分隔符的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58192599/

相关文章:

python - 循环遍历 JSON 对象并将结果存储在 pandas dataframe 中

python-3.x - 在 Pandas 中对包含 Python `range` 或类似列表的列执行合并

Python - 这怎么能返回 -1?

python - 获取绑定(bind)到 Entry 小部件的 StringVar

python - 使用文本检索两个子元素之间的文本

python - 使用输入管道时如何替换 feed_dict?

python - MacOSX、Windows、Linux(Gnome) 和 python 上 GTK+ 中的状态图标

python-2.7 - Pandas.replace 不会从数据中删除字符

python - 使用 Python Pandas 处理双 for 循环

python - 将超链接添加到由 pandas dataframe to_excel 方法创建的 excel 表