首页 > 解决方案 > Pandas 'Str' 对象没有属性 'to_csv'

问题描述

目前,我想知道为什么 Pandas 在返回时无法将数据帧转换为 csv 文件AttributeError: 'str' object has no attribute 'to_csv'

我一直在尝试trends.to_string(index=False).to_csv('test.csv'))等以及其他一些示例,但它一遍又一遍地返回相同的内容。

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)

数据帧的输出

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

更新(包括main

标签: pythonpandas

解决方案


您可能想要,下面的代码,您必须输入trends方法的参数:

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

推荐阅读