如何使用python替换向量数据0中的所有类似于()的字符

2024-04-27 00:16:19 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有3列数据我的文件.dat文件。它们的顺序如下。你知道吗

  234   -642  20.20
  233   -640  20.40
  233.4  --   20.60
  --    -646  20.80
  --    -642  21.00
  234   --    21.20
  342   --    21.40
  ...   ...   .....

我想用matplotlib python绘制它们,但在此之前我想替换它们 --所有列中的字符都是0,这样我就可以理解它何时变为0。在这个时候,我做它手动,但想做它编程。如有任何建议,我们将不胜感激。 谢谢


Tags: 文件数据顺序matplotlib编程绘制手动字符
3条回答

pandas是读取结构化数据的好库,与matplotlib配合得很好。
读取文件时,可以指定其他NaN值,这些值很容易替换为.fillna(0),例如:

In []:
import pandas as pd
df = pd.read_csv('myfile.dat', delim_whitespace=True, header=None, na_values=['--']).fillna(0)
df
Out[]:
       0      1     2
0  234.0 -642.0  20.2
1  233.0 -640.0  20.4
2  233.4    0.0  20.6
3    0.0 -646.0  20.8
4    0.0 -642.0  21.0
5  234.0    0.0  21.2
6  342.0    0.0  21.4

In []:
df.plot()
Out[]:

enter image description here

你只是在找这样的东西吗?你知道吗

infile = open('test.dat')
outfile = open('clean.dat', 'w')
for line in infile:
    outfile.write(line.replace('--', '0'))

outfile.close()
infile.close()

clean.dat现在将数据中的“-”替换为“0”,例如:

  234   -642  20.20
  233   -640  20.40
  233.4  0   20.60
  0    -646  20.80
  0    -642  21.00
  234   0    21.20
  342   0    21.40

编辑: 要打开并覆盖某个文件,可以执行以下操作:

FILE = 'test.dat

f = open(FILE)
infile =  f.read() #infile is one big string with the whole doc

f.close()
outfile = open(FILE, 'w') #this will OVERWIRTE the original!!
outfile.write(infile.replace('--', '0'))

outfile.close()

加载数据文件后,将每列中的'--'替换为0

new_column = [0 if cell=='--' else cell for cell in old_column]

此语句使用conditional operator和生成器表达式[f(x) for x in a_list]。你知道吗

相关问题 更多 >