4

I have a pandas dataframe as following named as df

enter image description here

I want to convert this dataframe to a bytes string which is having type bytes i.e when I enter type(df) it should give me an output of Bytes instead of pandas.core.frame.DataFrame The output should look like following:

b'Age,Height,Weight,City\r\n23,5.45,67,New York\r\n' 
5
  • df is constructed with pandas.DataFrame(). Thus, it is a pandas.core.frame.DataFrame. could you provide a minimum working example of your input data also? you'd need to transform the columns of the dataframe/concatenate it somehow to produce output of your definition. Commented Jul 21, 2020 at 11:41
  • if you take this dataframe as a csv and read it using data = open('df.csv', 'rb').read() it gives you data in b'Age,Height,Weight,City\r\n23,5.45,67,New York\r\n' form which is what I want directly from dataframe instead of csv. Commented Jul 21, 2020 at 11:44
  • so you could write the dataframe into a temp.csv 'df.to_csv("temp.csv")' and then read it as you presented? also there seems to be something similar in stackoverflow.com/questions/34666860/… Commented Jul 21, 2020 at 11:50
  • that is not a solution Commented Jul 21, 2020 at 11:51
  • I know, I'm just trying to clarify the problem, because you did not provide a working example Commented Jul 21, 2020 at 11:58

1 Answer 1

11

You can convert your dataframe to csv string, then to bytes:

bytes(df.to_csv(line_terminator='\r\n', index=False), encoding='utf-8') 
Sign up to request clarification or add additional context in comments.

3 Comments

Your answer is almost 99% right, however the output i am getting from your code is also throwing ',' in the start which is not what i expect. the output from your code is -----> b',Age,Height,Weight,City\r\n23,5.45,67,New York\r\n'
I want output as -----> b'Age,Height,Weight,City\r\n23,5.45,67,New York\r\n'
@NikhilMangire pass index=False into to_csv. See update.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.