【问题标题】:TypeError: 'str' object does not support item assignment, pandas operationTypeError: 'str' object 不支持 item 赋值,pandas 操作
【发布时间】:2020-05-15 09:00:47
【问题描述】:

我正试图从一个金融网站上获取一些金融数据。我想操纵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)

有什么方法可以解决吗?请帮忙!谢了!

【问题讨论】:

  • 你在哪里声明你的 str var 在你的代码中?为什么你使用 is 作为一个函数? str(代码) ... ?请给我们更多关于你声明它的 str var 的数据......它是一个函数还是一个数组?
  • 我在 years = ['2019', '2018', '2017', '2016'] 的位置声明了它,我想分别用年份命名我的 df[col]。 @ZINEMahmoud
  • 您的 str(code) str(year) ... 对您的代码没有意义? ....您的代码中的 str 是什么?那是我的问题吗?它是函数还是 var ?你不能只设置它而不定义它
  • 'str' 仍然是未定义的先生
  • 看来我不太明白'str'没有定义。我的编码能力仍然很业余。你能给我一些提示吗? @ZINEMahmoud

标签: python-3.x string pandas dataframe


【解决方案1】:

您的代码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)

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

【讨论】:

    猜你喜欢
    • 2016-05-11
    • 2021-10-13
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2018-12-06
    • 1970-01-01
    相关资源
    最近更新 更多