1

I have a DataFrame where one column contains the string values "True" and "False". However, when I export the DataFrame to Excel using pd.to_excel and open the file in Excel, these values appear as Excel logical values (TRUE/FALSE in uppercase).

As a result, comparing the value "True" from pandas with the Excel "TRUE" returns False

This issue doesn't happen when exporting to CSV; everything remains as plain text.

import pandas as pd

d = {'col1': [1, 2], 'col2': [3, 4], 'col3': ['True','False']}
df = pd.DataFrame(data=d)

writer = pd.ExcelWriter(r'H:\ExcelTest2.xlsx', engine = 'xlsxwriter')
df.to_excel(writer, index=False, sheet_name='Sheet1')
writer.save()

To reproduce:

  1. Run the code to generate the Excel file.
  2. Open the file with Excel
  3. In column 4 (a new column), manually type True
  4. Compare column 3 with 4
  5. Notice the answer is always False

My question:

How can I export data from pandas to Excel without pandas converting "True"/"False" strings into Excel boolean values (TRUE/FALSE)? I want the values to remain text exactly as they are in the DataFrame.

1
  • 1
    Try to share an example with code. Commented Nov 27, 2018 at 13:56

1 Answer 1

1

You can convert your strings before writing to Excel like in following example:

import pandas as pd
import numpy as np

df = pd.DataFrame({'A': ['True', 'False', 'True']})
df['A'].dtype
#dtype('O')

df['A'] = df['A'] == 'True'
df['A'].dtype
#dtype('bool')
Sign up to request clarification or add additional context in comments.

3 Comments

Please execute my code. open xlsx file and in column 4 write regular "True" then compare Column3 (from pandas) with True you just wrote. it will be False
Well, your answer gave me some idea what could go wrong in mode code. In some point my data was str so i had to use .astype(bool) before export to excel which makes "True" equal to excel "True"
@Drac0 I've miss-typed the True it should be 'True'. Edited.

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.