2

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. 

3 Answers 3

2
companies_column = list(df.iloc[:,4].values)
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0
  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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.