Read strings of length n as n columns in pandas

Viewed 142

I have a .txt file of the following format:

10101011
00101010
11001100
00101101

How do I read this directly as a dataframe of n (integer) columns? i.e.

   0  1  2  3  4  5  6  7
0  1  0  1  0  1  0  1  1
1  0  0  1  0  1  0  1  0
2  1  1  0  0  1  1  0  0
3  0  0  1  0  1  1  0  1
3 Answers

One possible solution is use read_fwf with specify number of columns with parameter widths:

import pandas as pd

temp = """10101011
00101010
11001100
00101101"""

#after testing replace 'pd.compat.StringIO(temp)' with 'filename.csv'
df = pd.read_fwf(pd.compat.StringIO(temp), header=None, widths= [1] * 8)
    
print (df)
   0  1  2  3  4  5  6  7
0  1  0  1  0  1  0  1  1
1  0  0  1  0  1  0  1  0
2  1  1  0  0  1  1  0  0
3  0  0  1  0  1  1  0  1

You could do it using a simple list comprehension

import pandas as pd

text = """10101011
00101010
11001100
00101101"""

df = pd.DataFrame(list(line) for line in text.split('\n'))

print(df)

   0  1  2  3  4  5  6  7
0  1  0  1  0  1  0  1  1
1  0  0  1  0  1  0  1  0
2  1  1  0  0  1  1  0  0
3  0  0  1  0  1  1  0  1

Using from_records:

import pandas as pd

df = pd.DataFrame.from_records(temp.split())
>>> df
   0  1  2  3  4  5  6  7
0  1  0  1  0  1  0  1  1
1  0  0  1  0  1  0  1  0
2  1  1  0  0  1  1  0  0
3  0  0  1  0  1  1  0  1
Related