1

I have a file which I'm trying to convert into data frame using pandas. It is inside a loop and returns me the output as shown below. Here is the code I'm using:

import pandas as pd
import csv
with open('File.tbl', 'r') as  f:
    P=list(f)
    del P[0]
for o in P:
    M=o.split()
    B= M[:4]             #selecting specific columns only
    E= pd.DataFrame(B)   #converting into DataFrame
    print(E)
    G.to_csv('para.csv', sep=',')

Here the tbl file is not tab seperated and to create a tab separation, I've to convert it into list. Here is the reult I'm getting:

0    B
1  244
2    S
3    0
     0
0    B
1  245
2    A
3    0

The expected output is like this:

0    B   244  S  0

0    B   245  A  0

Any help will be highly appreciated.

1 Answer 1

1

Try this:

import pandas as pd
import csv
df=pd.DataFrame()
with open('File.tbl', 'r') as  f:
    P=list(f)
    del P[0]
for o in P:
    M=o.split()
    B= M[:4]             #selecting specific columns only
    df = pd.concat([df,pd.DataFrame(B).T])    #converting into DataFrame
df.to_csv('para.csv', sep=',')
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks for the reply, This is the result I'm getting: 0 B 244 S 0 0 1 2 3 0 B 245 A 0 Any idea how to remove those 0,1, 2, 3.
@Dustrokes Edited mine.
It worked, but now it's not getting converted into CSV file, the error I'm getting is this: 'str' object has no attribute 'to_csv'. I can convert the file using with open statements but would prefer to directly convert it into csv.
@Dustrokes Edited mine, just viewd SO
Hey, any idea how to convert the strings into csv file by directly using to_csv command?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.