0

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?

5
  • P.S. The dataframe is large and has more than 25 million rows so writing a "for i in rows" loop is not an option. Commented Apr 27, 2018 at 18:10
  • 2
    df['B'] = df['B'].apply(lambda t: (' '*(4-len(str(t)))+str(t))) and similar for the third column, then save to csv Commented Apr 27, 2018 at 18:11
  • @mathisfun You are a genius. I loved how simple and efficient this command is. Thank you so much! Commented Apr 27, 2018 at 18:23
  • @mathisfun I wish I could pick your answer as the best answer but since it is posted as a comment but not an answer, I cannot Commented Apr 27, 2018 at 18:24
  • 1
    I added it. Feel free to give me some street cred. :) Commented Apr 27, 2018 at 18:27

1 Answer 1

3
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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.