使用python 2.7(通过np.array.astype函数)将txt列数据(字符串)转换为int

使用python 2.7(通过np.array.astype函数)将txt列数据(字符串)转换为int,python,Python,答案如下: import numpy as np import matplotlib.pyplot as plt f=open('00001.txt','r') if f==0: print("fail to open the file") else: print("file successfully opened") data=f.readlines() a = np.array(data) yvec1 = a.astype(int)

答案如下:

import numpy as np
import matplotlib.pyplot as plt  
f=open('00001.txt','r')

if f==0:
    print("fail to open the file")
else:
    print("file successfully opened")
    data=f.readlines()
    a = np.array(data)  
    yvec1 = a.astype(int)
    print(yvec1)
if f.close()==0:
    print("fail to close file")
else:
    print("file closed")
原始文本数据为:

ValueError: invalid literal for int() with base 10: '\n'

请尝试
a=np.array(data.split('\n'))
-问题是,当您以这种方式读取文件时,每行都包含新行符号
\n

您的代码是错误的,因为/n不能转换为int,因为它不是数字字符

试试这个:

name
716
722
729
732
730
728
729
733
735
737
737
739
741
744
747
749
747
742
742
742
742
741
739
738
736
734
732
...

您应该这样做,因为它更像“蟒蛇”:


您知道
data
是一个列表,您正在列表上调用
int()
data=f.readlines()
data_int = []
for item in data:
  data_int.append(int(item))
a = np.array(data_int)  
yvec1 = a.astype(int)
print(yvec1)
import numpy as np
import matplotlib.pyplot as plt


# Read your file properly
with open('00001.txt', 'r') as f
    # Retrieve the data without '\n' code (it was your problem)
    data = f.read().splitlines()
    # Load it in numpy
    a = np.array(data)
    # Do what you want with it
    yvec1 = a.astype(int)