1

I have .csv file contains currency and its rate. I want to extract the highlighted data from .csv and store it in variable.

How can I do that using Python?

enter image description here

I am currently a beginner in Python and I have so many things to learn.

2 Answers 2

1

Considering your .csv file only contains such table, you can open and get the data you want from it in Python using Pandas:

import pandas as pd
# Open the csv file
data = pd.read_csv("yourfilename.csv")
# Get the value
data.loc[data["Curr"] == "GBP", "Rates"][1]

For solving your issue with missing names in the header, you can skip the first row and add custom column names:

# Open the csv file
colnames = ["currency", "rate"]
data = pd.read_csv("yourfilename.csv", names=colnames, skiprows=(0,))
# Get the value
data.loc[data["currency"] == "GBP", "rate"][1]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the ideas! I forgot to tell that the first column has no actually name. I just put 'Curr' because it looks like Currency. How do I add the naming of first column sir?
If you have an incomplete header, you can skip the first row and add your own column names. I'll edit my answer to include this step.
1

The best (and common way) to do it is by using a package called Pandas.

You can install it by typing pip install pandas in your terminal.

If you are using the Anaconda Environment it should be already installed. Skip this "Anaconda" passage if you don't know what I'm talking about (Google it eventually).

With pandas you can do this:

# Import pandas package
import pandas as pd

# Read your file as a dataframe
myDataframe = pd.read_csv("filename.csv")

# Convert 'Rates' column to float (if needed)
myDataframe = myDataframe.astype({"Rates":"float"})

# Extract the 'interesting' row by using this notation
interestingRow = myDataframe[myDataframe["Curr"] == "GBP"]

# Extract the rate value from the row
theRate = interestingRow["Rates"]

1 Comment

Thanks for the ideas! I forgot to tell that the first column has no actually name. I just put 'Curr' because it looks like Currency. How do I add the naming of first column sir?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.