问题
I have a pandas dataframe (df) that looks like this:
A B C
0 1 10 1234
1 2 20 0
I want to save this dataframe in a fixed format. The fixed format I have in mind has different column width and is as follows:
"one space for column A's value then a comma then four spaces for column B's values and a comma and then five spaces for column C's values"
Or symbolically:
-,----,-----
My dataframe above (df) would look like the following in my desired fixed format:
1, 10, 1234
2, 20, 0
How can I write a command in Python that saves my dataframe into this format?
回答1:
df['B'] = df['B'].apply(lambda t: (' '*(4-len(str(t)))+str(t)))
df['C'] = df['C'].apply(lambda t: (' '*(5-len(str(t)))+str(t)))
df.to_csv('path_to_file.csv', index=False)
来源:https://stackoverflow.com/questions/50067957/saving-a-pandas-dataframe-in-fixed-format-with-different-column-widths