rar3009
rar3009

Reputation: 27

Trying to split data with spaces into two different columns

I am trying to split my data which has numbers that are separated by 1 or more number of spaces into two different columns. It has name called DUT0 and I want to seperate it into two columns with names "Temperature" and "Voltage".

This is my code:

import pandas as pd
import re as r
from matplotlib import pyplot as plt
file = pd.read_table('sample.txt')
print(file)
file[['vtg', 'temp']] = file['DUT0'].str.split('\s+-\s+', expand=True)
print(file)

I keep getting this error: "Columns must be same length as key"

The data has numbers with 1/more spaces in between the two numbers. I just want to separate the 2 numbers into 2 columns to make a list of the second column.

The text looks like this:

DUT0

5600    2.3

5650   12.9

5700  23891

There are different number of white spaces in between these two numbers.

Expected output :

Temp Vtg

5600 2.3

5650 12.9

5700 23891

Upvotes: 0

Views: 126

Answers (1)

jcaliz
jcaliz

Reputation: 4021

Use read_table specifying the sep as a regular expression:

file = pd.read_table('sample.txt',
                     sep='\s+',
                     engine='python',
                     skiprows=1,
                     header=None,
                     names=['vtg', 'temp'])
file.head()

#   vtg     temp
# 0 5600    2.3
# 1 5650    12.9
# 2 5700    23891.0

Upvotes: 1

Related Questions