0

I have a .txt file with data ordered as below:

R11
R12
R13
R14
R15
R16
R17
R18
R19
R20

I need to iterate over rows in the textfile to fill the columns per row. In other words, the data need to be transformed to a pandas DataFrame looking like this:

| Column1 | Column2 | Column3 | Column4 | Column5 |
|---------|---------|---------|---------|---------|
| R11     | R12     | R13     | R14     | R15     |
| R16     | R17     | R18     | R19     | R20     |

My code starts with the following. After running, I now have a list of all rows called data, but how to get a pandas DataFrame as above as output?

with open('data.txt','r') as file:
    data = file.read().split('\n')
1
  • 2
    pd.DataFrame(pd.read_csv('data.txt', names=[0]).values.reshape(-1,5)) Commented Feb 3, 2021 at 17:16

2 Answers 2

1

You can read text file using pd.read_csvand name column name

pd.DataFrame(pd.read_csv('data.txt', names=[0]).values.reshape(-1,5), columns = ['Column1','Column2', 'Column3', 'Column4', 'Column4'])

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. In the real data this answer gives not the precise output I desired. Empty rows are excluded and float number between 0 and 1 are all 0. Therefore, I accepted another answer. But with exactly this data, your answer is perfect. Thanks!
0

You are almost there! After reading the data in as a list you can split the list in chunk of 5s and then pass it in the pd.DataFrame()

with open('data.txt','r') as file:
    data = file.read().split('\n')

# split the list in chunks of 5s
chunks = [data[x:x+5] for x in range(0, len(data), 5)]

# pass the chunks in pd.DataFrame and specify the columns names of the OP:
pd.DataFrame(chunks, columns=["Column1", "Column2", "Column3", "Column4", "Column5"])

P.S. I assumed there was a typo in the last column as it appears to be named again Column4, but here I named it Column5. You can always name it Column4 if this is what you needed.

1 Comment

It was a typo, edited it. Worked out great and was in line with my initial attempts. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.