首页 > 解决方案 > TypeError: 'str' object 不支持 item 赋值,pandas 操作

问题描述

我正试图从一个金融网站上获取一些金融数据。我想操纵df['__this value__']。我自己做了一些研究,我理解这个错误很好,但我真的不知道如何解决它。这就是我的代码的样子:

import requests
import bs4
import os
import pandas as pd


def worker_names(code=600110):

    ......

    df = pd.DataFrame({'class': name_list})
    worker_years(df)


def worker_years(df, code=600110, years=None):

    if years is None:
        years = ['2019', '2018', '2017', '2016']
        url = 'http://quotes.money.163.com/f10/dbfx_'\
              + str(code) + '.html?date='\
              + str(years) + '-12-31,'\
              + str(years) + '-09-30#01c08'

        ......

        df['{}-12-31'.format(years)] = number_list  # this is where the problem is
        df = df.drop_duplicates(subset=['class'], keep=False)
        df.to_csv(".\\__fundamentals__\\{:0>6}.csv".format(code),
                  index=False, encoding='GBK')
        print(df)

if __name__ == '__main__':
    pd.set_option('display.max_columns', None)
    pd.set_option('display.unicode.ambiguous_as_wide', True)
    pd.set_option('display.unicode.east_asian_width', True)

    fundamental_path = '.\\__fundamentals__'
    stock_path = '.\\__stock__'

    worker_names(code=600110)

有什么方法可以解决吗?请帮忙!一切都好!

标签: python-3.xstringpandasdataframe

解决方案


你的代码df['{}-12-31'.format(years)] = number_list演示了一个很好的例子,you can't make 2 variables on both side of the equation.试试这个:

df_year = pd.DataFrame({'{}'.format(year): number_list})
df = pd.concat([df, df_year], axis=1)

使用数据框工作,有许多不同的方法可以获得相同的结果。


推荐阅读