How do I load specific rows from a .txt file in Python?

2024/4/15 0:32:21

Say I have a .txt file with many rows and columns of data and a list containing integer values. How would I load the row numbers in the text file which match the integers in the list?

To illustrate, say I have a list of integers:

a = [1,3,5]

How would I read only rows 1,3 and 5 from a text file into an array?

The loadtxt routine in numpy let's you both skip rows and use particular columns. But I can't seem to find a way to do something along the lines of (ignoring incorrect syntax):

new_array = np.loadtxt('data.txt', userows=a, unpack='true')

Thank you.


Given this file:


You can use the csv module to get the desired np array:

import csv
import numpy as npdesired=[1,3,5]
with open('/tmp/test.csv', 'r') as fin:reader=csv.reader(fin)result=[[int(s) for s in row] for i,row in enumerate(reader) if i in desired]print(np.array(result))   


[[ 4  5  6][10 11 12][16 17 18]]

Related Q&A

How to check in python if Im in certain range of times of the day?

I want to check in python if the current time is between two endpoints (say, 8:30 a.m. and 3:00 p.m.), irrespective of the actual date. As in, I dont care what the full date is; just the hour. When I c…

Python __class__()

In Pythons documentation __class__ is described as an attribute. In the object type (the metaclass), __class__ appears to be a method.If we do:>>> class Foo:pass>>> a = Foo() >>…

how to handle ever-changing password in sqlalchemy+psycopg2?

I inherited some code that uses sqlalchemy with psycopg2, which needs to run on AWS. RDS Postgres supports iam-based authentication, but the way it does it is rather kludgy: you request a temporary pas…

How to determine which compiler was requested

My project uses SCons to manage the build process. I want to support multiple compilers, so I decided to use AddOption so the user can specify which compiler to use on the command line (with the defaul…

Does pytest have anything like google tests non-fatal EXPECT_* behavior?

Im more familiar with the google test framework and know about the primary behavior pair they support about ASSERT_* vs EXPECT_* which are the fatal and non-fatal assert modes.From the documentation:Th…

Radon transformation in python

Here is a dummy code:def radon(img):theta = np.linspace(-90., 90., 180, endpoint=False)sinogram = skimage.transform.radon(img, theta=theta, circle=True)return sinogram # end defI need to get the sinogr…

Librosa raised OSError(sndfile library not found) in Docker

Im trying to write the Dockerfile for a small python web project and there is something wrong with the dependencies. Ive been doing some search on the internet and it said that Librosa library requires…

Implementing Tags using Django rest framework

TDLR : what is the best way to implement tags in django-rest-framework. where the tags has a created_by field which is the currently authenticated user.I am trying to achieve a very simple/common thing…

Python audiolab install, unable to install (or find) libsndfile on Mac OSX

Trying to install scikits.audiolab-0.11.0 on Mac, bit it requires libsndfile: I did install libsndfile supposedly, using libsndfile_python-1.0.0-py2.7-macosx10.5.m…

Connecting to events of another widget

This is most likely a duplicate question, but I have to ask it because other answers arent helping in my case, since I am new to pyqt (switched from tkinter few days ago).I am wondering if is it possib…