Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating list from imported CSV file with pandas

I am trying to create a list from a CSV. This CSV contains a 2 dimensional table [540 rows and 8 columns] and I would like to create a list that contains the values of an specific column, column 4 to be specific.

I tried: list(df.columns.values)[4], it does mention the name of the column but i’m trying to get the values from the rows on column 4 and make them a list.

import pandas as pd
import urllib
#This is the empty list
company_name = [] 

#Uploading CSV file 
df = pd.read_csv('Downloads\Dropped_Companies.csv')

#Extracting list of all companies name from column "Name of Stock"
companies_column=list(df.columns.values)[4] #This returns the name of the column. 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  1. So for this you can just add the following line after the code you’ve posted:

    company_name = df[companies_column].tolist()
    

    This will get the column data in the companies column as pandas Series (essentially a Series is just a fancy list) and then convert it to a regular python list.

  2. Or, if you were to start from scratch, you can also just use these two lines

    import pandas as pd
    
    df = pd.read_csv('Downloads\Dropped_Companies.csv')
    company_name = df[df.columns[4]].tolist()
    
  3. Another option: If this is the only thing you need to do with your csv file, you can also get away just using the csv library that comes with python instead of installing pandas, using this approach.

If you want to learn more about how to get data out of your pandas DataFrame (the df variable in your code), you might find this blog post helpful.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading