john
john

Reputation: 131

Access latest entry of name X in CSV file

I have a csv file, the columns are:

Date,Time,Spread,Result,Direction,Entry,TP,SL,Bal

And typical entries would look like:

16/07/21,01:25:05,N/A,No Id,Null,N/A,N/A,N/A,N/A
16/07/21,01:30:06,N/A,No Id,Null,N/A,N/A,N/A,N/A
16/07/21,01:35:05,8.06,Did not qualify,Long,N/A,N/A,N/A,N/A
16/07/21,01:38:20,6.61,Trade,Long,1906.03,1912.6440000000002,1900.0,1000.0
16/07/21,01:41:06,N/A,No Id,Null,N/A,N/A,N/A,N/A

How would I access the latest entry where the Result column entry is equal to Trade preferably without looping through the whole file?

If it must be a loop, it would have to loop backwards from latest to earliest because it is a large csv file.

Upvotes: 1

Views: 122

Answers (3)

suvayu
suvayu

Reputation: 4654

I suggest you use pandas, but in case you really cannot, here's an approach.

Assuming the data is in data.csv:

from csv import reader

with open("data.csv") as data: 
     rows = [row for row in reader(data)]

col = rows[0].index('Result')
res = [row for i, row in enumerate(rows) if i > 0 and row[col] == 'Trade']

I advise against using this, way too brittle.

Upvotes: 1

Lorenzo Donadio
Lorenzo Donadio

Reputation: 86

Load your .csv into a pd.DataFrame and you can get all the rows where df.Results equals Trade like this:

df[df.Result == 'Trade']

if you only want the last one then list use .iloc

df[df.Result == 'Trade'].iloc[-1]

I hope this is what you are looking for.

Upvotes: 1

U13-Forward
U13-Forward

Reputation: 71580

If you want to use pandas, try using read_csv with loc:

df = pd.read_csv('yourcsv.csv')
print(df.loc[df['Result'] == 'Trade'].iloc[[-1]])

Upvotes: 1

Related Questions