Python - Read CSV Columns Into List - GeeksforGeeks
文章推薦指數: 80 %
In this method we will import the csv library and open the file in reading mode, then we will use the DictReader() function to read the data of ... Skiptocontent CoursesGeekWeek2022ForWorkingProfessionalsDSAClasses(Live)SystemDesign(Live)JavaBackendDeveloper(Live)FullStack(Live)ExploreMoreLiveCoursesDSA(Self-Paced)SDETheory(Self-Paced)AllDevelopmentCourses(Self-Paced)ExploreMoreSelf-PacedCoursesForStudentsCompetitiveProgramming(Live)GATECourse2023(Live)DataScience(Live)ExploreMoreLiveCoursesDSA(Self-Paced)CIP(Self-Paced)JAVA/Python/C++(Self-Paced)ExploreMoreSelf-PacedCoursesSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#SQLScalaPerlGoLanguageKotlinWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesBusinessStudies(Class11th)BusinessStudies(Class12th)CSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersUPSCGeographyNotesHistoryNotesScience&Tech.NotesEthicsNotesPolityNotesEconomicsNotesUPSCPreviousYearPapersSSCCGLSSCCGLSyllabusGeneralStudiesEnglishReasoningSubjectwisePracticePapersPreviousYearPapersBankingExamsSBIClerkSBIClerkSyllabusGeneralAwarenessEnglishQuantitativeAptitudeReasoningAbilitySBIClerkPracticePapersSBIPOSBIPOSyllabusGeneralAwarenessEnglishQuantitativeAptitudeReasoningAbilityPreviousYearPapersSBIPOPracticePapersIBPSPOIBPSPO2022SyllabusEnglishNotesReasoningNotesPreviousYearPapersMockQuestionPapersIBPSClerkIBPSClerkSyllabusEnglishNotesPreviousYearPapersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblemsContests HomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningJavaScriptSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesPython–ReadCSVColumnsIntoListPython–ReadCSVColumnintoListwithoutheaderHowtoreadcsvfilewithPandaswithoutheader?DecimalFunctionsinPython|Set2(logical_and(),normalize(),quantize(),rotate()…)NetworkX:PythonsoftwarepackageforstudyofcomplexnetworksDirectedGraphs,MultigraphsandVisualizationinNetworkxPython|VisualizegraphsgeneratedinNetworkXusingMatplotlibVisualizeGraphsinPythonGraphPlottinginPython|Set1GraphPlottinginPython|Set2GraphPlottinginPython|Set3PlottinggraphusingSeaborn|PythonBoxplotvisualizationwithPandasandSeabornBoxPlotinPythonusingMatplotlibHowtogetcolumnnamesinPandasdataframePythonprogramtofindnumberofdaysbetweentwogivendatesPython|Differencebetweentwodates(inminutes)usingdatetime.timedelta()methodPython|datetime.timedelta()functionComparingdatesinPythonPython|ConvertstringtoDateTimeandvice-versaConvertthecolumntypefromstringtodatetimeformatinPandasdataframeAddingnewcolumntoexistingDataFrameinPandasCreateanewcolumninPandasDataFramebasedontheexistingcolumnsPython|CreatingaPandasdataframecolumnbasedonagivenconditionSelectingrowsinpandasDataFramebasedonconditionsPythonmap()functionReadJSONfileusingPythonTakinginputinPythonPython–ReadCSVColumnsIntoListPython–ReadCSVColumnintoListwithoutheaderHowtoreadcsvfilewithPandaswithoutheader?DecimalFunctionsinPython|Set2(logical_and(),normalize(),quantize(),rotate()…)NetworkX:PythonsoftwarepackageforstudyofcomplexnetworksDirectedGraphs,MultigraphsandVisualizationinNetworkxPython|VisualizegraphsgeneratedinNetworkXusingMatplotlibVisualizeGraphsinPythonGraphPlottinginPython|Set1GraphPlottinginPython|Set2GraphPlottinginPython|Set3PlottinggraphusingSeaborn|PythonBoxplotvisualizationwithPandasandSeabornBoxPlotinPythonusingMatplotlibHowtogetcolumnnamesinPandasdataframePythonprogramtofindnumberofdaysbetweentwogivendatesPython|Differencebetweentwodates(inminutes)usingdatetime.timedelta()methodPython|datetime.timedelta()functionComparingdatesinPythonPython|ConvertstringtoDateTimeandvice-versaConvertthecolumntypefromstringtodatetimeformatinPandasdataframeAddingnewcolumntoexistingDataFrameinPandasCreateanewcolumninPandasDataFramebasedontheexistingcolumnsPython|CreatingaPandasdataframecolumnbasedonagivenconditionSelectingrowsinpandasDataFramebasedonconditionsPythonmap()functionReadJSONfileusingPythonTakinginputinPythonPython–ReadCSVColumnsIntoListViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: MediumLastUpdated: 17Sep,2021ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle CSVfilestorestabulardata(numbersandtext)inplaintext.Eachlineofthefileisadatarecord.Eachrecordconsistsofoneormorefields,separatedbycommas.Theuseofthecommaasafieldseparatoristhesourceofthenameforthisfileformat.Inthisarticle,wewillreaddatafromaCSVfileintoalist.Wewillusethepanda’slibrarytoreadthedataintoalist. FileUsed:file.Method1:UsingPandasHere,wehavetheread_csv()functionwhichhelpstoreadtheCSVfilebysimplycreatingitsobject.Thecolumnnamecanbewritteninsidethisobjecttoaccessaparticularcolumn,thesameaswedoinaccessingtheelementsofthearray.Pandaslibraryhasafunctionnamedastolist()thatconvertsthedataintoalistthatcanbeusedasperourrequirement.So,wewillusethistoconvertthecolumndataintoalist.Finally,wewillprintthelist.Approach:Importthemodule.ReaddatafromCSVfile.Convertitintothelist.Printthelist.Belowistheimplementation:Python3#importingmodulefrompandasimport* #readingCSVfiledata=read_csv("company_sales_data.csv") #convertingcolumndatatolistmonth=data['month_number'].tolist()fc=data['facecream'].tolist()fw=data['facewash'].tolist()tp=data['toothpaste'].tolist()sh=data['shampoo'].tolist() #printinglistdataprint('Facecream:',fc)print('Facewash:',fw)print('Toothpaste:',tp)print('Shampoo:',sh)Output:Method2:UsingcsvmoduleInthismethodwewillimportthecsvlibraryandopenthefileinreadingmode,thenwewillusetheDictReader()functiontoreadthedataoftheCSVfile.Thisfunctionislikearegularreader,butitmapstheinformationtoadictionarywhosekeysaregivenbythecolumnnamesandallthevaluesaskeys.Wewillcreateemptylistssothatwecanstorethevaluesinit.Finally,weaccessthekeyvaluesandappendthemintotheemptylistsandprintthatlist.Python3#importingthemoduleimportcsv #openthefileinreadmodefilename=open('company_sales_data.csv','r') #creatingdictreaderobjectfile=csv.DictReader(filename) #creatingemptylistsmonth=[]totalprofit=[]totalunit=[] #iteratingovereachrowandappend#valuestoemptylistforcolinfile: month.append(col['month_number']) totalprofit.append(col['moisturizer']) totalunit.append(col['total_units']) #printinglistsprint('Month:',month)print('Moisturizer:',totalprofit)print('TotalUnits:',totalunit)Output:MyPersonalNotes arrow_drop_upSave LikeNext Python-ReadCSVColumnintoListwithoutheaderRecommendedArticlesPage:22,Jan2023,Feb2106,Apr2225,Mar2109,Sep2106,May2123,Feb2103,Jul1813,Jan2116,Apr2123,Jan1906,Jul2003,Mar2116,Apr2116,Dec2110,Apr2020,Oct2016,Dec2120,Sep1812,Sep1830,Apr2028,Apr2122,Sep2102,Apr20ArticleContributedBy:adityaprasad1308@adityaprasad1308VotefordifficultyCurrentdifficulty: MediumEasy Normal Medium Hard ExpertImprovedBy:anikakapoorrajeev0719singhArticleTags:Pickedpython-csvTechnicalScripter2020PythonTechnicalScripterPracticeTags:pythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register
延伸文章資訊
- 1Python import csv to list - Stack Overflow
Using the csv module: import csv with open('file.csv', newline='') as f: reader = csv.reader(f) d...
- 2Python – Convert CSV to List of Lists - Finxter
To read a CSV to a nested list in pure Python, open the file using open('my_file.csv') , read all...
- 3Reading Rows from a CSV File in Python - GeeksforGeeks
- 4How to read a `csv` file into a list in Python - Adam Smith
Call open(filepath, mode) with a .csv file path as filepath and "r" as mode to return a file obje...
- 5Python - Read CSV Columns Into List - GeeksforGeeks
In this method we will import the csv library and open the file in reading mode, then we will use...