Python 类型错误:';str';对象不支持项分配和添加列

Python 类型错误:';str';对象不支持项分配和添加列,python,pandas,Python,Pandas,我是熊猫队的新手…我正在尝试向df(df['new_col'])添加一个新柱…但当我出现此错误时: import requests import pandas as pd import json res = requests.get("http://api.etherscan.io/api?module=account&action=txlist&address=0xddbd2b932c763ba5b1b7ae3b362eac3e8d40121a&startblock=

我是熊猫队的新手…我正在尝试向df(df['new_col'])添加一个新柱…但当我出现此错误时:

import requests
import pandas as pd
import json

res = requests.get("http://api.etherscan.io/api?module=account&action=txlist&address=0xddbd2b932c763ba5b1b7ae3b362eac3e8d40121a&startblock=0&endblock=99999999&sort=asc&apikey=YourApiKeyToken")
j = res.json()
df = pd.DataFrame(j['result'])
#add column
df = df['new_col'] = '12'
print(df.head())

Traceback (most recent call last):
  File "pandas_csv.py", line 8, in <module>
    df = df['new_col'] = '12'
TypeError: 'str' object does not support item assignment
导入请求
作为pd进口熊猫
导入json
res=requests.get(“http://api.etherscan.io/api?module=account&action=txlist&address=0xddbd2b932c763ba5b1b7ae3b362eac3e8d40121a&startblock=0&endblock=99999999&sort=asc&apikey=YourApiKeyToken")
j=res.json()
df=pd.DataFrame(j['result'])
#添加列
df=df['new_col']='12'
打印(df.head())
回溯(最近一次呼叫最后一次):
文件“pandas_csv.py”,第8行,在
df=df['new_col']='12'
TypeError:“str”对象不支持项分配
有什么想法吗?

换个新的

df = df['new_col'] = '12'


为了解释为什么会发生这种情况,这里有一个简单的问题MCVE:

d = {1: "a"}
d = d[1] = "3"

TypeError: 'str' object does not support item assignment
发生这种情况的原因是,如上所述,
df=df['new\u col']='12'
等同于:

df = "3"
df['new_col'] = '12'
现在,错误发生的原因应该显而易见了<在
'new\u col'
赋值发生之前,会用字符串覆盖code>df

df = "3"
df['new_col'] = '12'