0

I have a string bytearray(b'onefish,twofish,greenfish,bluefish\r\n1,2,3,4') I get this string from an encrypted csv file using the pgpy library.

I need my dataframe to look like this.

      onefish twofish greenfish bluefish
0     1       2       3         4

So far I use multiple for loops that make lists that I then put into a dictionary.

How can approach this using: df = pd.Dataframe(bytearray(b'onefish,twofish,greenfish,bluefish\r\n1,2,3,4') to get the output I want above?

Jeffyx
  • 78
  • 2
  • 9

2 Answers2

5
  • from given data. Split data by '\r\n'.
  • assuming First row is always header pass that as columns and rest of the rows as data.
>>>import pandas as pd
>>>b = b'onefish,twofish,greenfish,bluefish\r\n1,2,3,4\r\n5,6,7,8' 
>>>data = list(map(lambda x: x.split(','),b.decode('utf-8').split("\r\n")))
>>>pd.DataFrame(data[1:], columns=data[0])

    onefish     twofish     greenfish   bluefish
0      1          2            3           4
1      5          6            7           8
Poojan
  • 3,366
  • 2
  • 17
  • 33
4

You can use io.BytesIO as far as I'm aware:

import pandas as pd
import io

df = pd.read_csv(io.BytesIO(bytearray(b'onefish,twofish,greenfish,bluefish\r\n1,2,3,4\r\n5,6,7,8\r\n9,10,11,12')))

print(df)

   onefish  twofish  greenfish  bluefish
0        1        2          3         4
1        5        6          7         8
2        9       10         11        12
manwithfewneeds
  • 1,137
  • 1
  • 7
  • 10