Home > Blockchain >  How to load string to a pandas df with columns names
How to load string to a pandas df with columns names

Time:12-24

I have the following string that I read from file:

 `something` `something_else` /dev.py
 `something2` `something_else2` /tasks.py

I want to create a df that looks like:

       1        2              3
`something` `something_else` /dev.py
`something2` `something_else2` /tasks.py

I tried:

f = open("te.txt", "r")
string = f.read()
df = pd.DataFrame([x.split(' ') for x in string.split('\n')])

but this doesn't work as expected. It gives me df of 5 columns. It should be only 3 columns with 2 rows.

CodePudding user response:

Try read_csv with the following options:

df = pd.read_csv('te.txt', sep='\s ', engine='python',
                 header=None, skipinitialspace=True)
print(df)

# Output:
              0                  1          2
0   `something`   `something_else`    /dev.py
1  `something2`  `something_else2`  /tasks.py
  • Related