我有 .csv 檔案包含貨幣及其匯率。我想從 .csv 中提取突出顯示的資料并將其存盤在變數中。
我如何使用 Python 做到這一點?

我目前是 Python 的初學者,我有很多東西要學習。
uj5u.com熱心網友回復:
最好的(也是常見的)方法是使用一個名為Pandas的包。
您可以通過在終端中輸入pip install pandas來安裝它。
如果您使用的是 Anaconda 環境,它應該已經安裝。如果你不知道我在說什么(最終谷歌它),請跳過這個“Anaconda”段落。
使用熊貓,您可以這樣做:
# 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"]
uj5u.com熱心網友回復:
考慮到您的 .csv 檔案僅包含此類表,您可以使用 Pandas 在 Python 中打開并從中獲取您想要的資料:
import pandas as pd
# Open the csv file
data = pd.read_csv("yourfilename.csv")
# Get the value
data.loc[data["Curr"] == "GBP", "Rates"][1]
為了解決標題中缺少名稱的問題,您可以跳過第一行并添加自定義列名稱:
# 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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/320773.html
