如何格式化数据帧的文件输出?

2024-09-22 10:26:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试从一个熊猫数据帧输出一个文件,它看起来像这样,我一直在尝试用不同的格式将它写入一个文件

     codi      Acumulado Ahorro    Prestamo Fondo 1  Prestamo Empresa 1
0    0151           1425.76             28320                0.00
1    2361           1158.49              4100             1200.00
2    2663            737.10              2903              429.00
3    2792            897.75              1950              627.00
4    0737           1266.54              7859                0.00
5    5073            779.00               557              754.00
6    2819           1274.70               958                0.00
7    1558            738.51             10242              676.00
8    4105            695.49              2382                0.00
9    4146           1170.08              8623                0.00
10   0528           1337.17              1042                0.00

我试过这样的方法: df.to_csv(output_file, sep = '|') 但是输出就像一个csv,而不是“,”我得到“|”

我正在努力实现这个输出:

0E0151
A1425.76|2019|Acumulado Ahorro
A0.00|2019|Prestamo Empresa 1
A28320.00|2019|Prestamo Fondo 1

其中0E必须连接到codi列中的数字,然后将字母“A”连接到Acumulado ahorro列中的数字,然后连接字符“|”和列的名称,依此类推

如何创建此格式以便将其写入实际文件


Tags: 文件csvto数据方法dfoutput格式
2条回答

对于这种不寻常的文件格式,您需要一个自定义的写入例程,例如:

with open("output.txt", "w") as file:
    for i in range(len(df)):
        file.write("0E" + str(df["codi"][i]) + "\n")
        for c in list(df.columns.values[1:]):
            file.write("A" + str(df[c][i]) + "|2019|" + c + "\n")

我非常肯定,你必须创建自己的自定义格式化程序。希望这个答案能提供一些指导

def format_row(row):
    first_line = f"0E{int(row['codi'])}" + '\n'
    second_line = [f"A{row[el]}|2019|{el}" for el in ['Acumulado Ahorro', 'Prestamo Fondo 1', 'Prestamo Empresa 1']]
    second_line = '\n'.join(second_line)
    return f"{first_line}{second_line}"

format_text = df.apply(format_row, axis=1)

for text in format_text:
    print(text)

输出:

0E151
A1425.76|2019|Acumulado Ahorro
A28320.0|2019|Prestamo Fondo 1
A0.0|2019|Prestamo Empresa 1
0E2361
A1158.49|2019|Acumulado Ahorro
A4100.0|2019|Prestamo Fondo 1
A1200.0|2019|Prestamo Empresa 1
...

您可以轻松地将format_text保存到所需的任何文本文件中

相关问题 更多 >