How to Import a CSV File into Python using Pandas

文章推薦指數: 80 %
投票人數:10人

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



請為這篇文章評分?