'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. 


Solution 1:[1]

  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.

Solution 2:[2]

companies_column = list(df.iloc[:,4].values)

Solution 3:[3]

I think that you can try this for getting all the values of a specific column:

companies_column = df[{column name}]

Replace "{column name}" with the column you want to access the values of.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 LeonardoVaz
Solution 3 Vatsal Dutt