Python--numpy(np.loadtxt)

这篇文章介绍了Python的numpy库中np.loadtxt函数的使用方法,包括读取文本文件、设置分隔符、跳过行数、选择列以及unpack参数的用法。示例展示了如何处理全数字和含字母的文本数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文参考:http://blog.youkuaiyun.com/u010025211/article/details/51498790

import numpy as np

np.loadtxt 

       作用是把文本文件(*.txt)读入并以矩阵或向量的形式输出。它有几个参数:skiprows,delimiter,usecoles和unpack。skiprows作用是跳过头行。在默认情况下是通过空格来分割列的,如果想通过其他来分割列则需要通过delimiter来设置。如果你想跳过几列来读取则需要用usecoles来设置。

        正常情况下该返回的是二维矩阵,若设置了unpack=True将返回各列。例子如下:

1.全是数字的

                                                                               

 >>> np.loadtxt(loadtxt.txt')                                                               >>> np.loadtxt('loadtxt.txt', skiprows=1,delimiter=',')                 
array([[ 1.,  2.,  3.,  4.],                                                                               array([[ 4.,  7.,  5.,  9.],                                                                   
       [ 4.,  7.,  5.,  9.],                                                                                              [ 7.,  2.,  2.,  2.]])
       [ 7.,  2.,  2.,  3.]])

>>> np.loadtxt('loadtxt.txt', skiprows=1)
array([[ 4.,  7.,  5.,  9.],
       [ 7.,  2.,  2.,  3.]])

                                                                                                        

>>> np.loadtxt('loadtxt.txt',unpack=True)                               >>> np.loadtxt('loadtxt.txt',delimiter='\t')                            >>> np.loadtxt('loadtxt.txt',delimiter=',',usecols=[1,2,3][)
array([[ 1.,  4.,  3.],    array([ 1.,  4.,  7.])array([[ 2.,  3.,  5.], 

   [ 2.,  7.,  8.],         [ 5.,  6.,  6.],

   [ 3.,  2.,  9.]])   [ 5.,  6.,  8.],   

>>> a,b,c=np.loadtxt('loadtxt.txt',unpack=True)                                                                                                                                         [ 7.,  9.,  0.],  

 >>> a                [8.,  0.,  8.,]

array([ 1.,  4.,  3.]) >>> np.loadtxt('loadtxt.txt',delimiter=',',usecols=(0,3,4))

>>> b                                                                            array([[ 1.,  5.,  8.],
array([ 2.,  7.,  8.])                                                     [ 4.,  6.,  7.],
>>> c                           [ 1.,  8.,  9.],

array([ 3.,  2.,  9.])                                                                                                                                                                                      [ 8.,  0.,  5.],                       

                                                                   [ 8.,  8.,  1.]])


2.含字母


>>> a,b,c=np.loadtxt('loadtxt.txt',str,unpack=True)
>>> a
'k,l,g'
>>> np.loadtxt('loadtxt.txt',str,unpack=True)
array(['k,l,g', 'gan,j,k', 'j,u,o'], 
      dtype='|S7')
>>> np.loadtxt('loadtxt.txt',str)
array(['k,l,g', 'gan,j,k', 'j,u,o'], 
      dtype='|S7')
>>> np.loadtxt('loadtxt.txt',str,delimiter=',')
array([['k', 'l', 'g'],
       ['gan', 'j', 'k'],
       ['j', 'u', 'o']], 
      dtype='|S3')





要从如上所述格式的文本文件中读取三维点位置列表,并将其存储到一个合适的数据结构(例如Python中的列表或NumPy数组)中,可以按照以下步骤进行: ### 使用 Python 代码示例: #### 方法一:使用纯Python读取并解析文件 ```python def read_point_cloud_from_file(file_path): points = [] with open(file_path, 'r') as file: for line in file: # 去除行末的换行符并按空格分割 coords = line.strip().split() if len(coords) == 3: try: # 将字符串转换为浮点数并添加到points列表 point = [float(coord) for coord in coords] points.append(point) except ValueError: print(f"Warning: Could not convert line '{line}' to float.") return points # 示例用法 file_path = 'path_to_your_file.txt' point_cloud = read_point_cloud_from_file(file_path) # 打印前几个点以验证结果 for point in point_cloud[:5]: print(point) ``` #### 方法二:使用 NumPy 加速处理 如果你需要更高效的性能和更好的数值计算支持,可以考虑使用 `numpy` 库来加载数据: ```python import numpy as np def read_point_cloud_with_numpy(file_path): try: # 直接使用numpy.loadtxt读取文件,假设所有行都有三个浮点数 points = np.loadtxt(file_path) return points.tolist() if isinstance(points, np.ndarray) else [] except Exception as e: print(f"Error reading file: {e}") return [] # 示例用法 file_path = 'path_to_your_file.txt' point_cloud = read_point_cloud_with_numpy(file_path) # 打印前几个点以验证结果 for point in point_cloud[:5]: print(point) ``` 这两种方法都可以有效地将文本文件中的三维坐标读入内存,并且可以根据具体需求选择更适合的一种。如果你还需要对这些点云数据做进一步的处理或者可视化,建议使用像 `open3d`, `matplotlib` 或者其他专门用于点云处理的库。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值