代码之家  ›  专栏  ›  技术社区  ›  Laurent R

根据字段位置将数据帧导出为txt

  •  0
  • Laurent R  · 技术社区  · 7 年前

    pd.DataFrame 我想导出到一个文本文件,该文件中的字段按其位置/索引(不像 csv 带分离器)。 我可以创建一个这样做的函数,但它很可能会很慢,我希望熊猫能够集成这样的功能。

    pd.DataFrame({'a':[1,20,300], 'b':[10,200,30], 'c':[100, 2, 3]})
    export(df, index_position={'a':0, 'b':5, 'c':9}, 'sometxtfile.txt')
    

    0123456789012 ## index position as a reference
    a    b   c    ## Where the variable must be
    ------------- ## The file starts after that
    1    10  100  ## a is starting at index 0
    20   200 2    ## b is starting at index 5
    300  30  3    ## c is starting at index 9
    

    任何帮助都将不胜感激

    1 回复  |  直到 7 年前
        1
  •  0
  •   Laurent R    7 年前

    这很管用,但不太优雅。欢迎评论,欢迎批评。

    df = pd.DataFrame({'a':[1,20,300], 'b':[10,200,30], 'c':[100, 2, 3]})
    positions = {0:'a', 5:'b', 9:'c'}
    

    def exporttxt(df, positions):
      indexes = [x for x in positions.keys()]
      indexes.sort()
      df = df[[positions[x] for x in indexes]]
      toreturn = ''
      for _, line in df.iterrows():
        newline = ['{}'.format(line[positions[i]]).ljust(l) for i, l in zip(indexes, lengths)]
        toreturn = toreturn + '\n' + ''.join(newline)
      return toreturn
    
    print(exporttxt(df, positions))
    

    输出:

    1    10  100
    20   200 2
    300  30  3