How to Import CSV to List Python - Linux Hint

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

Line 1: We import the CSV module. Line 2 to 4: We open the sample.csv file in the read mode 'r'. Then we pass the read_obj to the ... WhatisaCSVFile? ACSVisa(commaseparatedvalues)fileinwhichdataisintheformofatabular.TheextensionoftheCSVfileis.csv.Thiscsvfileismostlyusedinthedataanalytics.Apartfromthedataanalytics,theCSVfilealsousedinthee-commerceapplicationbecauseit’sveryeasytohandleinalldifferenttypesofprogramminglanguages. WecanconverttheCSVtodifferentdatastructureslikealist,alistoftuplesandalistofdictionaries.WecanalsosavetheCSVwithouttheheaderorwiththeheaderasalist,andforthatwecanusesomemachinelearninglibrarieslikePandas. Example_1:ConverttheCSVtoListinPython ThebelowisaCSVsamplefilewhichwillbeusedtoconvertintoalist. "Month","1958","1959","1960" "JAN", 340, 360, 417 "FEB", 318, 342, 391 "MAR", 362, 406, 419 "APR", 348, 396, 461 "MAY", 363, 420, 472 "JUN", 435, 472, 535 "JUL", 491, 548, 622 "AUG", 505, 559, 606 "SEP", 404, 463, 508 "OCT", 359, 407, 461 "NOV", 310, 362, 390 "DEC", 337, 405, 432 importcsv withopen('sample.csv','r')asread_obj: csv_reader=csv.reader(read_obj) list_of_csv=list(csv_reader) print(list_of_csv) Output: [['JAN',340,360,417],['FEB',318,342,391],['MAR',362,406,419],['APR',348,396,461],['MAY',363,420,472],['JUN',435,472,535],['JUL',491,548,622],['AUG',505,559,606],['SEP',404,463,508],['OCT',359,407,461],['NOV',310,362,390],['DEC',337,405,432]] Line1:WeimporttheCSVmodule. Line2to4:Weopenthesample.csvfileinthereadmode‘r’.Thenwepasstheread_objtothecsv.reader()methodwhilecreatinganobjecttoreadtheCSVfile.ThenweconvertexplicitlytheCSVreaddataintoalistusingtypecast. Line6:TheoutputaboveshowsthatourCSVdataisnowsuccessfullyconvertedintothelist. Example_2:UsingPandastoReadCSVList Inthisexample,wearegoingtousethePandaslibrarytoreadtheCSVfileandconvertthemintoalist.TheCSVfileissamewhichwehaveusedintheexample_1(sample.csv). importpandasaspd df=pd.read_csv('sample.csv',delimiter=',') list_of_csv=[list(row)forrowindf.values] print(list_of_csv) Output: [['JAN',340,360,417],['FEB',318,342,391],['MAR',362,406,419],['APR',348,396,461],['MAY',363,420,472],['JUN',435,472,535],['JUL',491,548,622],['AUG',505,559,606],['SEP',404,463,508],['OCT',359,407,461],['NOV',310,362,390],['DEC',337,405,432]] Line1:WeimportthePandasmoduleaspd. Line2to3:WereadtheCSVfileusingthePandaslibraryread_csvandconverteditintoadataframe(df).Then,weconverteachrowintoalistandassigntheresulttothelist_of_csvvariable. Line4:TheoutputaboveshowsthatourCSVdataisnowsuccessfullyconvertedintothelist. Example_3:ConverttheCSVFileDataintoaListofTuples Inthisexample,wearegoingtoconverttheCSVfiledataintoalistoftuples.TheCSVfileissamewhichwehaveusedintheexample_1(sample.csv). importcsv withopen('sample.csv','r')asread_obj: csv_reader=csv.reader(read_obj) list_of_csv=list(map(tuple,csv_reader)) print(list_of_csv) Output: [('Month','"1958"','"1959"','"1960"'),('JAN',' 340',' 360',' 417'),('FEB',' 318',' 342',' 391'),('MAR',' 362',' 406',' 419'),('APR',' 348',' 396',' 461'),('MAY',' 363',' 420',' 472'),('JUN',' 435',' 472',' 535'),('JUL',' 491',' 548',' 622'),('AUG',' 505',' 559',' 606'),('SEP',' 404',' 463',' 508'),('OCT',' 359',' 407',' 461'),('NOV',' 310',' 362',' 390'),('DEC',' 337',' 405',' 432')] Line1:WeimporttheCSVmodule. Line2to4:Weopenthesample.csvfileinthereadmode‘r’.Wepasstheread_objtothecsv.reader()methodwhilecreatinganobjecttoreadthecsvfile.Then,weconverteachrowoftheCSVintoatupleusingamapfunctionandatlastconvertthewholedataintoalist. Line5:TheoutputaboveshowsthatourCSVdataisnowsuccessfullyconvertedintoalistoftuples. Example_4:ConverttheCSVfiledataintoalistofdictionaries Inthisexample,wearegoingtoconverttheCSVfiledataintoalistofdictionaries.TheCSVfileissamewhichwehaveusedintheexample_1(sample.csv). importcsv withopen('sample.csv','r')asread_obj: dict_reader=csv.DictReader(read_obj) list_of_dict=list(dict_reader)   print(list_of_dict) Output: [{'Month':'JAN','"1958"':' 340','"1959"':' 360','"1960"':' 417'},{'Month':'FEB','"1958"':' 318','"1959"':' 342','"1960"':' 391'},{'Month':'MAR','"1958"':' 362','"1959"':' 406','"1960"':' 419'},{'Month':'APR','"1958"':' 348','"1959"':' 396','"1960"':' 461'},{'Month':'MAY','"1958"':' 363','"1959"':' 420','"1960"':' 472'},{'Month':'JUN','"1958"':' 435','"1959"':' 472','"1960"':' 535'},{'Month':'JUL','"1958"':' 491','"1959"':' 548','"1960"':' 622'},{'Month':'AUG','"1958"':' 505','"1959"':' 559','"1960"':' 606'},{'Month':'SEP','"1958"':' 404','"1959"':' 463','"1960"':' 508'},{'Month':'OCT','"1958"':' 359','"1959"':' 407','"1960"':' 461'},{'Month':'NOV','"1958"':' 310','"1959"':' 362','"1960"':' 390'},{'Month':'DEC','"1958"':' 337','"1959"':' 405','"1960"':' 432'}] Line1:WeimporttheCSVmodule. Line2to4:Weopenthesample.csvfileinthereadmode‘r’.Then,wepasstheread_objtothe csv.DictReadermethodwhilecreatinganobjecttoreadthecsvfile.Thecsv.DictReaderautomaticallyconvertseachrowintoadictionary.Andthenweconvertthewholeresultsintoalist. Line6:TheoutputaboveshowsthatourCSVdataisnowsuccessfullyconvertedintoalistofdictionaries. Example_5:UsingthePandastoConverttheCSVFileDataintoaListwiththeHeader Inthisexample,wearegoingtousethePandaslibrarytoreadthecsvfileandconvertthemintoalistalongwithheader.TheCSVfileissamewhichwehaveusedintheexample_1(sample.csv). importpandasaspd df=pd.read_csv('sample.csv',delimiter=',') list_of_csv=[list(row)forrowindf.values] list_of_csv.insert(0,df.columns.to_list()) print(list_of_csv) Output: [['Month','"1958"','"1959"','"1960"'],['JAN',340,360,417],['FEB',318,342,391],['MAR',362,406,419],['APR',348,396,461],['MAY',363,420,472],['JUN',435,472,535],['JUL',491,548,622],['AUG',505,559,606],['SEP',404,463,508],['OCT',359,407,461],['NOV',310,362,390],['DEC',337,405,432]] Line1:WeimportthePandasmoduleaspd. Line2to4:WereadthecsvusingthePandaslibraryread_csvandconverteditintoadataframe(df).Thenweconverteachrowintoalistandassigntheresulttothelist_of_csvvariable.Now,inthenextline,weareaddingonelistitematposition0ofthelist_of_csv(listvariable).ThislistitemisthenameofcolumnsoftheCSVfiledata. Line5:TheoutputaboveshowsthatourCSVdataisnowsuccessfullyconvertedintothelistandthefirstlistvalueisthenameofcolumns(header). Conclusion Inthisblog,wehavelearntabouthowtoconvertthecsvfiledataintoalist.Wehaveseenalldifferentmethodsoflistdatastructureliketuples,dictionaries.WehavealsoseenthesamemethodwiththePandaslibrary.ThenwehavealsoseenhowtoaddtheheaderoftheCSVintothelist. Abouttheauthor ShekharPandey Viewallposts RELATEDLINUXHINTPOSTS PyTorchTutorialKerasTutorialt-SNESklearnKNNinSklearnCrossValidationinSklearnPandasUnionPandasrolling().apply()Function



請為這篇文章評分?