提问人:edgar 提问时间:11/16/2023 更新时间:11/16/2023 访问量:38
将具有不同数据类型的 pandas 数据帧左对齐写入 txt 文件
Write a pandas dataframe with different datatypes left aligned into a txt-file
问:
具有以下数据帧:
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
不过,第一列实际上应该被视为字符串:向左对齐并采用指定的格式(这是另一个程序的输入,它像这样请求它)。有没有办法有效地做到这一点?
答:
1赞
Sash Sinha
11/16/2023
#1
您可以将第一列转换为字符串,然后使用 str.ljust
:
import pandas as pd
data = {
'Column1': ['1e10', '123.1105', '0.5e-2', '0'],
'Column2': ['String1', 'String3', 101, 'String4']
}
df = pd.DataFrame(data)
df = df.astype(str)
max_widths = [max(len(str(col)), *df[col].astype(str).apply(len)) for col in df.columns]
with open('example.txt', 'w') as file:
file.write('------- Data --------\n')
header = ' '.join(
col.ljust(max_widths[i]) for i, col in enumerate(df.columns))
file.write(header + '\n')
for index, row in df.iterrows():
row_str = ' '.join(
str(value).ljust(max_widths[i]) for i, value in enumerate(row))
file.write(row_str + '\n')
输出:
------- Data --------
Column1 Column2
1e10 String1
123.1105 String3
0.5e-2 101
0 String4
评论
0赞
edgar
11/16/2023
谢谢,它几乎按预期工作。如果标题比内容长,则它不再完全对齐。这可以通过将此行 ' max_widths = [max(df[col].apply(len)) for col in df.columns] ' 更改为 ' max_widths = [max(len(str(str(col)), *df[col].astype(str).apply(len)) for col in df.columns] '
0赞
Sash Sinha
11/16/2023
好!将列标题的长度合并到计算中是个好主意。max_widths
评论