【发布时间】:2021-04-14 02:50:36
【问题描述】:
我有一个文本文件,其中有多个分隔符分隔值。从此我只想读取管道分隔值
数据是这样的,例如: ' 10|10|10|10|10|10|10|10|10;10:10:10,10,10,10 ... 等 '
我只想将最多 8 个管道分隔的值作为数据框读取,并忽略带有“;,:”的值。我该怎么做?
【问题讨论】:
我有一个文本文件,其中有多个分隔符分隔值。从此我只想读取管道分隔值
数据是这样的,例如: ' 10|10|10|10|10|10|10|10|10;10:10:10,10,10,10 ... 等 '
我只想将最多 8 个管道分隔的值作为数据框读取,并忽略带有“;,:”的值。我该怎么做?
【问题讨论】:
这将是一个两步过程。首先读取以|为分隔符的csv
df = pd.read_csv(StringIO(
"10|10|10|10|10|10|10|10|10;10:10:10,10,10,10"
), delimiter='|', header=None)
0 1 2 3 4 5 6 7 8
0 10 10 10 10 10 10 10 10 10;10:10:10,10,10,10
然后通过删除[;,:]之后的字符串来更新最后一列
df.iloc[:, -1] = df.iloc[:, -1].str.replace(r'[;,:].*', '', regex=True)
0 1 2 3 4 5 6 7 8
0 10 10 10 10 10 10 10 10 10
如果您知道必须忽略的确切字符,则可以使用comment 属性,如下所示。该 1 字符字符串之后的所有内容都将被忽略。
df = pd.read_csv(StringIO(
"10|10|10|10|10|10|10|10|10;10:10:10,10,10,10"
), delimiter='|', header=None, comment=';')
df
0 1 2 3 4 5 6 7 8
0 10 10 10 10 10 10 10 10 10
【讨论】:
usecols,如果您知道要阅读的确切列号,例如usecols=[3,4,5]
这比其他提议的解决方案更长,但也可能更快,因为它只读取需要的内容。它将结果收集为一个列表,但它可能是另一种容器类型:
df = "10,10,10,10|10|10|10|10|10|10|10|10;10:10:10,10,10,10"
coll = []
start = 0
prevIdx = -1
while True:
try:
idx = df.index("|", start)
if prevIdx >= 0:
n = int(df[prevIdx+1:idx])
if isinstance(n, int): coll.append(n)
start = idx+1
prevIdx = idx
except:
break;
print(coll) # ==> [10, 10, 10, 10, 10, 10, 10]
【讨论】: