python-3.x - 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)
有什么方法可以解决吗?请帮忙!一切都好!
解决方案
你的代码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)
使用数据框工作,有许多不同的方法可以获得相同的结果。
推荐阅读
- c# - How to handle exception in AWS Lambda in C# for reprocessing
- javascript - 我的对象数组中的值总和出现 NaN 问题
- c++ - Finding main diagonal matrix using pointer array
- javascript - ASP.net 剃须刀页面和多选,在选择中发布所有项目
- javascript - 使用视口缩放 div 位置
- android - Android 如何在六边形内绘制三角形?
- cmake - cmake 在 Linux 中搜索库的默认文件夹是什么?
- javascript - 从函数中获取价值
- python - Little logic issue with Panda duplicates on python
- iis - Session expiring at random dotnet core 3.1