Python Pandas, write DataFrame to fixed-width file (to_fwf?)

前端 未结 7 943
予麋鹿
予麋鹿 2020-11-30 11:25

I see that Pandas has read_fwf, but does it have something like DataFrame.to_fwf? I\'m looking for support for field width, numerical precision, a

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-30 11:45

    found a very simple solution! (Python). In the code snapped I am trying to write a DataFrame to a positional File. "finalDataFrame.values.tolist()" will return u a list in which each row of the DataFrame is turn into an another list just a [['Camry',2019,'Toyota'],['Mustang','2016','Ford']]. after that with the help of for loop and if statement i am trying to set its fix length. rest is obvious!

     with open (FilePath,'w') as f:
        for i in finalDataFrame.values.tolist():
            widths=(0,0,0,0,0,0,0)
            if i[2] == 'nan':
                i[2]=''
                for h in range(7):
                    i[2]= i[2] + ' '
            else:
                x=7-len(str(i[2]))
                a=''
                for k in range(x):
                   a=a+' '
                i[2]=str(i[2])+a
    
            if i[3] == '':
                i[3]=''
                for h in range(25):
                    i[3]=i[3]+' '
            else:
                x = 25 - len(i[3])
                print(x)
                a = ''
                for k in range(x):
                    a = a + ' '
                print(a)
                i[3] = i[3] + a
    
    
            i[4] = str(i[4])[:10]
    
            q="".join("%*s" % i for i in zip(widths, i))
            f.write(q+'\n')
    

提交回复
热议问题