Click here to Skip to main content
15,900,536 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have this data below:
TIMESTEP
0
id mass y
246 0.782024 0.498339
216 0.794396 0.505147
.....

which I want to extract with columnwise arrangement in pandas dataframe like this:
TIMESTEP id mass y
0        246 0.782024 0.498339


What I have tried:

I have this code which is working fine if I have only three columns but not working for more than three columns and showing error: ValueError: not enough values to unpack (expected 3, got 1)

Python
with open('particle.txt', 'r') as fin:
    f_data = fin.read()
    columns = ["TIMESTEP", "id", "mass", "y"]
    data = []
    previous_line = ""

for line in f_data.split("\n"):
    if columns[0] in previous_line and columns[1] not in line:
        data.append({"TIMESTEP": line})
    elif columns[1] in previous_line and columns[0] not in line:
        data[len(data)-1]["id"], data[len(data)-1]["mass"], data[len(data)-1] ["y"] = 
        line.split(" ")
    elif all(col not in line for col in columns):
        data.append({"TIMESTEP": data[len(data)-1]["TIMESTEP"]})
        data[len(data)-1]["id"], data[len(data)-1]["mass"], data[len(data)-1] ["y"] = 
        line.split(" ")

    previous_line = line

df_1 = pd.DataFrame(data)
Posted
Updated 1-Apr-22 23:28pm
v4
Comments
Richard MacCutchan 2-Apr-22 5:26am    
You need to show the data that is being processed when the error occurs, and indicate the actual line where kit occurs. It also makes your code more readable if you use <pre> tags around it as I have done on your behalf.
Richard MacCutchan 2-Apr-22 8:00am    
The problem is with your for loop and the if block. You forgot to check when you read the line whether there is any actual data in it. A blank line will cause the error message that you see.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900