2

I am trying to read an excel file, convert it into csv and load its head:

df = pd.read_excel("final.xlsx", sheet_name="NewCustomerList")
# df = df.to_csv()
print(df.head(3))

Without converting to csv, the results look like this:

  Note: The data and information in this document is reflective of a hypothetical situation and client.  \
0                                         first_name                                                                                                                              
1                                            Chickie                                                                                                                              
2                                              Morly     

However, if I uncomment the conversion, I get an error that:

'str' object has no attribute 'head'

I am guessing its because of the first line of the data. How else can I convert this properly and read it?

  • In the docs, to_csv returns None or a string. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html – vanntile Jul 24 '20 at 16:28

2 Answers2

2

to_csv() is used to save a table to disk, it has no effect on memory-stored tables and returns None. So, you are changing your df variable to None with your commented line.

If you just want to display the table on screen in a specific format, perhaps take a look at to_string()

If you absolutely MUST have each row of your df as a comma-separated string then try a list comprehension:

my_csv_list = [','.join(map(str, row)) for row in df.itertuples()]

Beware of the csv format, if any datapoint contains a comma then you are in for a nightmare when decoding back to a table.

RichieV
  • 5,103
  • 2
  • 11
  • 24
1

According to the documentation, Pandas' to_csv() method returns None (nothing) or a string.

You could further need to use something like in this answer to turn the string into a dataframe again and use its head.

vanntile
  • 2,727
  • 4
  • 26
  • 48