具有以下数据帧:
import pandas as pd
data = {'Column1': ['1e10', '123.1105', '0.5e-2', '0'],
'Column2': ['String1', 'String3', 101, 'String4']}
df = pd.DataFrame(data)
我想把它写到一个txt文件中,其中的空格实际上只是空格(没有制表符等),每一列都左对齐:
------- Data --------
Column1 Column2
1e10 String1
123.1105 String3
0.5e-2 101
0 String4
我最接近这一点的是:
from tabulate import tabulate
# Format dataframe into table
table_content = tabulate(df.values.tolist(),tablefmt="plain")
# Write the txt-file
with open("example.txt", "w") as file:
file.write("------- Data --------")
file.write(table_content)
其中,输出为:
------- Data --------
Column1 Column2
1e+10 String1
123.111 String3
0.005 101
0 String4
但是,第一列实际上应该被视为字符串:左对齐并按照指定的格式(这是另一个请求它的程序的输入).有没有办法有效地做到这一点?