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
延伸文章資訊
- 1How to read CSV File into Python using Pandas | by Barney H.
- 2Creating a dataframe using CSV files - GeeksforGeeks
CSV files are the “comma-separated values”, these values are separated by commas, this file can b...
- 3Read CSV with Pandas - Python Tutorial
- 4[Day07]Pandas操作資料的函數! - iT 邦幫忙
使用Python進行資料分析系列第7 篇 ... 第七天了,上一篇提介紹了python內的一個套件pandas內兩個重要的資料結構, ... 使用 read_csv() 讀取一個CSV的檔案
- 5Python | 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...