0

I want to simply create a csv file from the constructed DataFrame so I do not have to use the internet to access the information. The rows are the lists in the code: 'CIK' 'Ticker' 'Company' 'Sector' 'Industry'

My current code is as follows:

def stockStat():
    doc = pq('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')

    for heading in doc(".mw-headline:contains('S&P 500 Component Stocks')").parent("h2"):
        rows = pq(heading).next("table tr")
        cik = []
        ticker = []
        coName = []
        sector = []
        industry = []

        for row in rows:
            tds = pq(row).find("td")
            cik.append(tds.eq(7).text())
            ticker.append(tds.eq(0).text())
            coName.append(tds.eq(1).text())
            sector.append(tds.eq(3).text())
            industry.append(tds.eq(4).text())



            d = {'CIK':cik, 'Ticker' : ticker, 'Company':coName, 'Sector':sector, 'Industry':industry}

        stockData = pd.DataFrame(d)

        stockData = stockData.set_index('Ticker')



stockStat()
6
  • 1
    so have you tried df.to_csv()? Commented May 26, 2015 at 8:02
  • stockData.to_csv( )? I have tried that but it finished the process and the csv doesn't show up in my IDE Commented May 26, 2015 at 8:03
  • 1
    yes have you tried that? pandas.pydata.org/pandas-docs/stable/generated/… Commented May 26, 2015 at 8:04
  • Are there certain parameters that I have to fill in to create the CSV? I run the df.to_csv( ) and like I said it isn't available in my IDE Commented May 26, 2015 at 8:07
  • 1
    Did you check the docs: pandas.pydata.org/pandas-docs/stable/generated/… it takes a path and various parameters for outputting, please have a look at that and come back if you're stuck Commented May 26, 2015 at 8:10

1 Answer 1

1

As EdChum already mentioned in the comments, creating a CSV out of a pandas DataFrame is done with the DataFrame.to_csv() method.

The dataframe.to_csv() method takes lots of arguments, they are all covered in the DataFrame.to_csv() method documentation. Here is a small example for you:

import pandas as pd

df = pd.DataFrame({'mycolumn': [1,2,3,4]})
df.to_csv('~/myfile.csv')

After this, the myfile.csv should be available in your home directory. If you are using windows, saving the file to 'C:\myfile.csv' should work better as a proof of concept.

Sign up to request clarification or add additional context in comments.

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.