-2

I want to create a dataframe like this:

df_finale = pd.DataFrame({'col0': '#define ', 'col1': var, 'col2': ' ', 'col3': var1})

where var is a dataframe of string and var1 is a dataframe made with numbers and then write it into a txt using python.

with open('C:\python\tests.txt', 'a') as f:
    df_string = df_finale.to_string(header=False, index=False)
    f.write(df_string)

but I see that in the txt the indentation is wrong. I'd like to have all the lines that begins on the left margin

3
  • can you give an example of the expected output? Commented May 24, 2024 at 11:10
  • ...or at least an example of var and var1? Commented May 24, 2024 at 11:11
  • Not knowing what your data looks like, the best I can suggest is adding the justify= parameter in df.to_string(). It should allow you to decide how you want the items in your .txt file to be aligned relative to their columns. There are more parameters that you can play around with listed here. Commented May 24, 2024 at 11:14

1 Answer 1

0

in the end I've found this solution

df=tabulate(df, showindex=False, headers=df.columns)

it worked for me, removing the index and maintaining a correct indentation on the left.

This solution was proposed here:

How to set the pandas dataframe data left/right alignment?

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.