首页 > 解决方案 > 根据字段位置将 Pandas 数据框导出到 txt

问题描述

我有一个pd.DataFrame我想导出到一个文本文件,该字段由它们的位置/索引定位(不像csv带分隔符的)。我可以创建一个功能来做到这一点,但它很可能会很慢,我希望 Pandas 能够集成这样的功能。

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

任何帮助将不胜感激

标签: pythonpandas

解决方案


这行得通,但它不是很优雅。欢迎评论,欢迎批评。

输入数据:

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

推荐阅读