yts*_*s61 6 string text text-alignment python-3.x pandas
我有一个 xlsx 文件。其中的文本格式是正常的,所有内容都向左对齐。现在我想从中提取一个字符串列并将其保存到一个txt文件中。我的代码如下:
import pandas as pd
import numpy as np
df = pd.read_excel('excel_file.xlsx',
sheet_name ='tab1'
)
df = df.drop(['L1','L2','L3'], axis=1)
# so that only 1 string column is left
w = open("output.txt", "w")
w.write (df.to_string(index=False, header=False))
w.close()
Run Code Online (Sandbox Code Playgroud)
好的,我已经成功创建了一个文本文件。但我的问题是,该文件中的所有内容都向右对齐,每个文本字符串前面有许多空格。示例如下,
Michael Jordan
Scottie Pippen
Dirk
Curry
Run Code Online (Sandbox Code Playgroud)
我想要的是正常的txt文件格式,如下所示:
Michael Jordan
Scottie Pippen
Dirk
Curry
Run Code Online (Sandbox Code Playgroud)
左对齐,无任何格式。
有人愿意帮忙吗?我已经尝试过许多其他解决方案,例如 set_properties、set_styles 等,并且阅读了许多类似这样的帖子How to leftalign a dataframe column in python? ,但我的问题没有解决。
如果您要写入的列名为 name COLUMN_NAME,您可以执行以下操作:
with open("output.txt", "w") as f_out:
f_out.write("\n".join(df["COLUMN_NAME"]))
Run Code Online (Sandbox Code Playgroud)
这会创建output.txt:
Michael Jordan
Scottie Pippen
Dirk
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3799 次 |
| 最近记录: |