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?
I am currently a beginner in Python and I have so many things to learn.
CodePudding user response:
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"]
CodePudding user response:
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]