How to Import a CSV File into Python using Pandas
文章推薦指數: 80 %
Step 1: Capture the File Path. Firstly, capture the full path where your CSV file is stored. · Step 2: Apply the Python code. Type/copy the ... Skiptocontent Menu NeedtoimportaCSVfileintoPython? Ifso,you’llseethecompletestepstoimportaCSVfileintoPythonusingPandas. Tostart,hereisasimpletemplatethatyoumayusetoimportaCSVfileintoPython: importpandasaspd df=pd.read_csv(r'PathwheretheCSVfileisstored\Filename.csv') print(df) Next,you’llseeanexamplewiththestepsneededtoimportyourfile. ImportingtheDataintoPython Solet’sbeginwithasimpleexample,whereyouhavethefollowingclientlistandsomeadditionalsalesinformationstoredinaCSVfile(wherethefilenameis‘Clients‘): PersonName Country Product PurchasePrice Jon Japan Computer $800 Bill US Tablet $450 Maria Canada Printer $150 Rita Brazil Laptop $1,200 Jack UK Monitor $300 Ron Spain Laptop $1,200 Jeff China Laptop $1,200 Carrie Italy Computer $800 Marry Peru Computer $800 Ben Russia Printer $150 StepstoImportaCSVFileintoPythonusingPandas Step1:CapturetheFilePath Firstly,capturethefullpathwhereyourCSVfileisstored. Forexample,let’ssupposethataCSVfileisstoredunderthefollowingpath: C:\Users\Ron\Desktop\Clients.csv You’llneedtomodifythePythoncodebelowtoreflectthepathwheretheCSVfileisstoredonyourcomputer. Don’tforgettoincludethe: Filename(ashighlightedingreen).Youmaychooseadifferentfilename,butmakesurethatthefilenamespecifiedinthecodematcheswiththeactualfilename Fileextension(ashighlightedinblue).Thefileextensionshouldalwaysbe‘.csv’whenimportingCSVfiles Step2:ApplythePythoncode Type/copythefollowingcodeintoPython,whilemakingthenecessarychangestoyourpath. Hereisthecodeforourexample(youcanfindadditionalcommentswithinthecodeitself): importpandasaspd df=pd.read_csv(r'C:\Users\Ron\Desktop\Clients.csv')#readthecsvfile(put'r'beforethepathstringtoaddressanyspecialcharactersinthepath,suchas'\').Don'tforgettoputthefilenameattheendofthepath+".csv" print(df) Step3:RuntheCode Finally,runthePythoncodeandyou’llget: PersonNameCountryProductPurchasePrice 0JonJapanComputer$800 1BillUSTablet$450 2MariaCanadaPrinter$150 3RitaBrazilLaptop$1,200 4JackUKMonitor$300 5RonSpainLaptop$1,200 6JeffChinaLaptop$1,200 7CarrieItalyComputer$800 8MarryPeruComputer$800 9BenRussiaPrinter$150 OptionalStep:SelectSubsetofColumns NowwhatifyouwanttoselectasubsetofcolumnsfromtheCSVfile? Forexample,whatifyouwanttoselectonlythe PersonNameandCountrycolumns.Ifthat’sthecase,youcanspecifythosecolumnsnamesascapturedbelow: importpandasaspd data=pd.read_csv(r'C:\Users\Ron\Desktop\Clients.csv') df=pd.DataFrame(data,columns=['PersonName','Country']) print(df) You’llneedtomakesurethatthecolumnnamesspecifiedinthecodeexactlymatchwiththecolumnnameswithintheCSVfile.Otherwise,you’llgetNaNvalues. Onceyou’reready,runthecode(afteradjustingthefilepath),andyouwouldgetonlythePersonNameandCountrycolumns: PersonNameCountry 0JonJapan 1BillUS 2MariaCanada 3RitaBrazil 4JackUK 5RonSpain 6JeffChina 7CarrieItaly 8MarryPeru 9BenRussia AdditionalResources YoujustsawhowtoimportaCSVfileintoPythonusingPandas.Attimes,youmayneedtoimportExcelfilesintoPython.Ifthat’sthecase,youcancheckthefollowingtutorialthatexplainshowtoimportanExcelfileintoPython. OnceyouimportedyourfileintoPython,youcanstartcalculatingsomestatisticsusingPandas.Alternatively,youcaneasily exportPandasDataFrameintoaCSV. TofindoutmoreaboutusingPandasinordertoimportaCSVfile,pleasevisitthe PandasDocumentation. Tutorials PythonTutorials RTutorials JuliaTutorials BatchScripts RecentPosts HowtoIterateoveraListofListsinPython HowtoIterateoveraDictionaryinPython DATATOFISHPrivacyPolicy-CookiePolicy-TermsofServiceCopyright©|Allrightsreserved
延伸文章資訊
- 1在python利用Pandas 讀、寫csv檔及轉成list,對資料進行增減 ...
import pandas as pd. 首先引入pandas car_ = pd.read_csv('car.csv'). car.csv 為欲讀取之檔案,car_ 為DataFrame 格式...
- 2How to read CSV File into Python using Pandas | by Barney H.
- 3Python Pandas read_csv: Load Data from CSV Files
The Python Pandas read_csv function is used to read or load data from CSV files. We examine the c...
- 4Python | Read csv using pandas.read_csv() - GeeksforGeeks
To access data from the CSV file, we require a function read_csv() that retrieves data in the for...
- 5How to read CSV File into Python using Pandas | by Barney H.
Pandas read_csv() function imports a CSV file to DataFrame format. Here are some options: filepat...