1

I am trying to modify the following code (I am newbie at python, so try to teach me step by step)

import requests, json
import pandas as pd

class AjaxScraper():
    results = []

    def fetch(self, url):
        return requests.get(url)
    
    def parse(self, content):
        self.results = content['data']
                
        for entry in self.results:
            del entry['_id']
    
    def to_csv(self):
        df = pd.DataFrame(self.results)
        pd.to_csv('Table.csv', sep=',', encoding='utf-8',index = False)
    
    def start_me(self):
        response = self.fetch('https://scrapingkungfu.herokuapp.com/api?_=1576384789999')
        self.parse(response.json())
        self.to_csv()

if __name__ == '__main__':
    scraper = AjaxScraper()
    scraper.start_me()

I have got errors like that

  File "demo.py", line 24, in start_me
    self.to_csv()
  File "demo.py", line 19, in to_csv
    pd.to_csv('Table.csv', sep=',', encoding='utf-8',index = False)
AttributeError: module 'pandas' has no attribute 'to_csv'

I wonder why this error appears although I saw many codes that has to_csv in pandas package..!!

** This is a simple dataframe that I need to learn how to reorder the columns using the index of columns

import pandas as pd

name_dict = {
            'Name': ['a','b','c','d'],
            'Score': [90,80,95,20]
          }

df = pd.DataFrame(name_dict)

print (df)
YasserKhalil
  • 9,138
  • 7
  • 36
  • 95

1 Answers1

1

to_csv is a method of a DataFrame object, not of the pandas module. You need to create a dataframe

Reordering the Dataframe with your example

import pandas as pd

name_dict = {
            'Name': ['a','b','c','d'],
            'Score': [90,80,95,20]
          }

df = pd.DataFrame(name_dict)

print (df)

enter image description here

  1. The solution is creating a new data frame with our desired order
df = df[['Score', 'Name']]
Sivaram Rasathurai
  • 5,533
  • 3
  • 22
  • 45