Pandas/Python数据类型是否模仿NCHAR(X)?

2024-10-03 17:24:38 发布

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

我想读一个Excel并传递一些数据类型,比如CHAR(X),以告诉用空格填充其余部分的列,创建一个固定宽度的txt(其中每一列都有不同的宽度)

我现在正在做这件事

dictp7 = {
    "Tipo Registro": np.dtype("str"),
    "Tipo Registro 2": np.dtype("str")}

df = pd.read_excel("lote.xlsx", dtype=dictp7)

df["Tipo Registro"] = df["Tipo Registro"].astype("string").str.rjust(11, " ")
df["Tipo Registro 2"] = df["Tipo Registro 2"].astype("string").str.rjust(160, " ")
open("lote.txt", "w").write(df.to_string(header=False))

(这是简短的版本) 我对每一列都这样做,效果很好

但也许有更好的解决方案,直接从指定的数据类型获取数据

在我看来,这是行不通的,但有点像:

dictp7 = {
    "Tipo Registro": str.rjust(11)}

那就好了

这是:

dictp7 = {
    "Tipo Registro": str.rjust(11).fillna(' ' * 11)}

那太棒了

为什么要这样做?
好吧,因为这个文件必须以特定的固定宽度格式(每列的宽度不同)呈现,流程才能工作。 不,我不能改变这个过程的工作方式。我只能遵循指导方针


Tags: txtdfstring宽度npexcel数据类型dtype