Converting an array index in binary and export into a csv format in PYTHON

Viewed 331

I have a CSV file with no header in a single and it contains data like this

25 35 56 45

what I am looking to do in spyder is

STEP 1: Import the csv file and store these vales in myArray.

 import pandas
    filename = 'myfile.csv'
    myArray = pandas.read_csv(filename)
    print(myArray)

STEP 2: convert the myArray indices to 4 bit binary numbers and export it in new CSV file.

[0,0,0,0; 
0,0,0,1; 
0,0,1,0; 
0,0,1,1]

Can anybody help me converting the array indices to binary data like this?

for k in range(1, 512):

    print (list('{0:8b}'.format(k)))

when i run this code it gives me output like

[' ', ' ', ' ', ' ', ' ', ' ', ' ', '1']
[' ', ' ', ' ', ' ', ' ', ' ', '1', '0']
[' ', ' ', ' ', ' ', ' ', ' ', '1', '1']
[' ', ' ', ' ', ' ', ' ', '1', '0', '0']

but I want it like ['0', '0', '0', '0', '0', '0', '0', '1'] and export this in csv file as number

1 Answers

You can't save 00000001 like a number to csv file. But you can save integers in binary string format and can easily turn it back to integers.

If you want to save indices like binary strings, you can do it this way:

import pandas as pd    

myArray = pd.read_csv(filename)
pd.Series(map(lambda x: bin(x), 
              myArray.index)).to_csv('output_file.csv', index=False, header=None)

To convert it back to integers:

myArray = pd.read_csv('output_file.csv', header=None)
myArray = myArray.applymap(lambda x: int(x, 2))
Related