Mike_Leigh
Mike_Leigh

Reputation: 223

TypeError: 'str' object does not support item assignment, pandas operation

I am trying to grab some finanical data off a financial website. I wanna manipulate df['__this value__']. I did some research myself, and I understand the error fine, but I really have no idea how to fix it. This is how my code is like:

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)

Is there any ways that I can work around? please help! THX ALL!

Upvotes: 0

Views: 323

Answers (1)

pepCoder
pepCoder

Reputation: 331

your codes df['{}-12-31'.format(years)] = number_list demostrate a very good example of you can't make 2 variables on both side of the equation. Try this:

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

work around with dataframe, there are many different ways to get the same result.

Upvotes: 1

Related Questions