Pandas 'Str' object has no attribute 'to_csv'

Question:

At the moment, I’m wondering why is Pandas not able to convert the dataframe to a csv file as it returns AttributeError: 'str' object has no attribute 'to_csv'

I’ve been trying trends.to_string(index=False).to_csv('test.csv')) etc and a few other examples others have given, but it returns the same thing over and over.

def main(url):
    google = GoogleAnalysis(url)
    codes = country_codes()
    return pd.concat([
        google.trends(country_code)
        for country_code in codes[:len(codes) // 2]
    ]) 

def trends(self,country_code):
    df = pd.DataFrame(
        self._retrieve_trends(country_code),
        columns=['Title', 'Search_Score'],
    )
    df['Country Code'] = country_code
    df['Platform'] = 'Google'
    return df

if __name__ == '__main__':
    trends = main('https://trends.google.com/trends/trendingsearches/daily/rss')
    trends.to_csv('k.csv').to_string(index=False)

Output of DataFrame

    Title         Search_Score    Country Code     Platform        
 アジアカップ 2019     20000           JP             Google             
     康華              2000           HK             Google              
   스피릿위시          2000            KR             Google              
 Michelle Obama       50000           US             Google             

Updated ( Include main )

Asked By: Minial

||

Answers:

You probably want, the below code, you have to enter the argument of trends method:

def trends(self,country_code):
        df = pd.DataFrame(
            self._retrieve_trends(country_code),
            columns=['Title', 'Search_Score'],
        )
        df['Country Code'] = country_code
        df['Platform'] = 'Google'
        return df

if __name__ == '__main__':
    trends = main(
 'https://trends.google.com/trends/trendingsearches/daily/rss')
trends.to_csv('k.csv')
Answered By: U12-Forward
import os
import glob
import pandas as pd
import numpy as np
import openpyxl as xls

path = r"D:\"

with open("file.csv", "w") as file:
 for root, dirname, files in os.walk(path):
         for x in files:      
             file.write(root + "\" + x + 'n')
             print(root + "\" + x + 'n')
      

file.close()
Answered By: Kshitiz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.