Home > Blockchain >  Accessing CSV row value by another value
Accessing CSV row value by another value

Time:07-10

Considering the following CSV data, how can I access the For Sale Amount value of a specific row by its ID?

Title,Price,For Sale Amount,Link,ID,Date Added
"First Sample Item",$358.35,2,https://www.website.com/release/FOO,FOO,Jul-09-2022 15:52:40
"Second Sample Item",$7.68,2,https://www.website.com/release/BAR,BAR,Jul-09-2022 15:52:40

I'm accessing the data from a local file as follows:

import csv

with open(csv_file_location, 'r ', newline='') as csv_file:
  csv_reader = csv.reader(csv_file)
  field_names = next(csv_reader)
  csv_writer = csv.writer(csv_file)
  ...

CodePudding user response:

If you can use other python packages, try this approach:

import pandas as pd
df = pd.read_csv(csv_file_location)
print(df.loc[df['ID']=='FOO',['For Sale Amount']])

If package is not available, you can install by using below pip install command in the terminal: pip install pandas

Hope it helps!

Code tried:

import pandas as pd
df = pd.DataFrame({"ID":['FOO','BAR','COOL'], "For Sale Amount":[200, 300, 500], "Col3": [89,90,91]})

print(df.loc[df['ID']=='FOO', ['For Sale Amount']])

Output:

For Sale Amount
0              200

CodePudding user response:

If you're really inclined to do it using the csv module, here you go.

import csv

with open('random_csv.csv', 'r') as fr:
    csvreader = csv.DictReader(fr)
    for_sale_by_ID = {col['ID'] : col['For Sale Amount'] for col in csvreader}
    
print(for_sale_by_ID)

# To access specific For Sale Amounts:
for_sale_amount_FOO = for_sale_by_ID['FOO']
print(f'FOO for sale amount : {for_sale_amount_FOO}')

Output:

{'FOO': '2', 'BAR': '2'}
FOO for sale amount : 2


However, for more tedious extractions, using the pandas module is much more efficient.

  • Related