TypeError:'str'对象不支持项目分配熊猫添加列

时间:2019-10-17 22:21:40

标签: 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=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

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

只需更换

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

作者

df['new_col'] = '12'

答案 1 :(得分:3)

仅是为了解释为什么会发生这种情况,下面是该问题的一个更简单的MCVE:

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

TypeError: 'str' object does not support item assignment

发生这种情况是因为,如here所述,df = df['new_col'] = '12'等同于:

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

现在,很明显为什么会发生错误。在df分配发生之前,'new_col'被字符串覆盖。