【问题标题】:How to add/edit text in pandas.io.parsers.TextFileReader如何在 pandas.io.parsers.TextFileReader 中添加/编辑文本
【发布时间】:2020-07-24 19:38:14
【问题描述】:

我有一个 CSV 格式的大文件。由于它是一个大文件(将近 7 GB),因此无法转换为 pandas 数据帧。

将熊猫导入为 pd df1 = pd.read_csv('tblViewPromotionDataVolume_202004070600.csv', sep='\t', iterator=True, chunksize=1000) 对于 df1 中的块: 打印(块)

df1 的类型是 pandas.io.parsers.TextFileReader

现在我想在此文件中编辑/添加/插入一些文本(新行),并将其转换回 pandas 数据框。请让我知道可能的解决方案。提前致谢。

【问题讨论】:

    标签: pandas pandas-datareader


    【解决方案1】:

    这里是DataFrame 称为块,所以处理使用它,最后写入文件使用DataFrame.to_csvmode='a' 用于追加模式:

    import pandas as pd 
    import os
    
    infile = 'tblViewPromotionDataVolume_202004070600.csv'
    outfile = 'out.csv'
    df1 = pd.read_csv(infile, sep='\t', iterator=True, chunksize=1000) 
    for chunk in df1: 
        print (chunk)
        #processing with chunk
    
        # https://stackoverflow.com/a/30991707/2901002
        # if file does not exist write header with first chunk
        if not os.path.isfile(outfile):
           chunk.to_csv(, sep='\t')
        else: # else it exists so append without writing the header
           chunk.to_csv('out.csv', sep='\t', mode='a', header=False)
    

    【讨论】:

    • 您好,感谢您的回复。
    • 我的问题是:我如何添加一行 (a;b;c;d;e) 例如作为该文件的标题,该文件现在是一个块。我无法在任何文本编辑器中打开该文件,因为它是一个大文件。因此我需要使用熊猫。我需要在顶部添加一行作为标题。
    • @nagasatishchilakamarti - 如果 DataFrame 中有 5 列,工作如何将 pd.read_csv(infile, sep='\t', iterator=True, chunksize=1000) 更改为 pd.read_csv(infile, sep='\t', iterator=True, chunksize=1000, names=['a',b','c','d','e'])
    猜你喜欢
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多