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

前端 未结 7 958
予麋鹿
予麋鹿 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:43

    Based on others' answer, here is the snippet I wrote, not the best in coding and performance:

    import pandas as pd
    import pickle
    import numpy as np
    from tabulate import tabulate
    
    
    left_align_gen = lambda length, value: eval(r"'{:<<>}'.format('''<>'''[0:<>])".replace('<>', str(length)).replace('<>', str(value)))
    right_align_gen = lambda length, value: eval(r"'{:><>}'.format('''<>'''[0:<>])".replace('<>', str(length)).replace('<>', str(value)))
    
    # df = pd.read_pickle("dummy.pkl")
    with open("df.pkl", 'rb') as f:
        df = pickle.load(f)
    
    # field width defines here, width of each field
    widths=(22, 255, 14, 255, 14, 255, 255, 255, 255, 255, 255, 22, 255, 22, 255, 255, 255, 22, 14, 14, 255, 255, 255, 2, )
    
    # format datetime
    df['CREATED_DATE'] = df['CREATED_DATE'].apply(lambda x: x.to_pydatetime().strftime('%Y%m%d%H%M%S'))
    df['LAST_MODIFIED_DATE'] = df['LAST_MODIFIED_DATE'].apply(lambda x: x.to_pydatetime().strftime('%Y%m%d%H%M%S'))
    df['TERMS_ACCEPTED_DATE'] = df['TERMS_ACCEPTED_DATE'].apply(lambda x: x.to_pydatetime().strftime('%Y%m%d%H%M%S'))
    df['PRIVACY_ACCEPTED_DATE'] = df['PRIVACY_ACCEPTED_DATE'].apply(lambda x: x.to_pydatetime().strftime('%Y%m%d%H%M%S'))
    
    
    # print(type(df.iloc[0]['CREATED_DATE']))
    # print(df.iloc[0])
    record_line_list = []
    # for row in df.iloc[:10].itertuples():
    for row in [tuple(x) for x in df.to_records(index=False)]:
        record_line_list.append("".join(left_align_gen(length, value) for length, value in zip(widths, row)))
    
    with open('output.txt', 'w') as f:
        f.write('\n'.join(record_line_list))
    

    Github gist

提交回复
热议问题