How to convert a pandas dataframe to a bytes string?

Viewed 3288

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'
1 Answers

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

bytes(df.to_csv(line_terminator='\r\n', index=False), encoding='utf-8')
Related