Read CSV from Specific Row

CSV read specific row

You could use a list comprehension to filter the file like so:

with open('file.csv') as fd:
reader=csv.reader(fd)
interestingrows=[row for idx, row in enumerate(reader) if idx in (28,62)]
# now interestingrows contains the 28th and the 62th row after the header

Reading a particular row in csv file with Python

'Paris SG' HomeTeam or AwayTeam:

import pandas as pd
df = pd.read_csv('F1.csv')
dh = df[['Date','HomeTeam','AwayTeam','FTHG','FTAG']]

index_list = dh[(dh['HomeTeam'] == 'Paris SG') | (dh['AwayTeam'] == 'Paris SG')].index.tolist()
dh_final = dh.iloc[index_list]

Pandas: How to read specific rows from a CSV file

Read the entire csv and do filtering like below

my_df =  pd.read_csv("example.csv")
my_df = my_df[my_df['hits']>20]

If you are having memory issues while reading, you can set chunksize parameter to read it in chunks

How to read csv file from a specific row using iterrows in python?

To address rows by index, simply use the handy iloc function and slicing:

import pandas as pd
file_read = pd.read_csv('1000_rows.csv')

for line,row in file_read.iloc[400:].iterrows():
print(line)

How to read a specific line of data from a csv file?

A filter should do the trick, something like

import csv
with open('details.csv', 'rt') as f:
reader = csv.reader(f)
selected_details = input("Enter student ID for details:\n")
results = filter(lambda x: selected_details in x, reader)
for line in results:
print(line)

Explanation:

Filter take an itterable (here reader) and will apply for each element of the itterable the lambda you give him and will return a new list "filtered". If the lambda return True the element will be returned in the filtered list.

A lambda is basically a dwarf-function (wiser, nerdier people will correct me on this over simplification but you get the idea) that return the one and only line you gave him.

So my lambda just does the operation "selected_details in x" that will return True if selected_details is in x and else False, you get the idea.



Related Topics



Leave a reply



Submit