0

我正在尝试将具有由 1 个或多个空格分隔的数字的数据拆分为两个不同的列。它的名称叫做 DUT0,我想将它分成两列,名称分别为“温度”和“电压”。

这是我的代码:

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)

我不断收到此错误:“列必须与键长度相同”

数据中的数字在两个数字之间有 1 个/多个空格。我只想将 2 个数字分成 2 列以列出第二列。

文本如下所示:

DUT0

5600    2.3

5650   12.9

5700  23891

这两个数字之间有不同数量的空格。

预期输出:

温度电压

5600 2.3

5650 12.9

5700 23891
4

1 回答 1

1

使用read_table将 指定sep为正则表达式:

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
于 2020-04-25T01:21:38.497 回答