我有一个Pandas dataframe,其中只有2列:第一列是名称,第二列是与名称相关的信息字典。添加新行很好,但是如果我尝试通过指定一个新字典来更新字典列,我将得到
ValueError: Incompatible indexer with Series
所以,准确地说,这就是我为了产生错误而做的事情:
import pandas as pd
df = pd.DataFrame(data=[['a', {'b':1}]], columns=['name', 'attributes'])
pos = df[df.loc[:,'name']=='a'].index[0]
df.loc[pos, 'attributes'] = {'c':2}
我找到了另一个可行的解决方案:
import pandas as pd
df = pd.DataFrame(data=[['a', {'b':1}]], columns=['name', 'attributes'])
pos = df[df.loc[:,'name']=='a'].index[0]
df.loc[:,'attributes'].at[pos] = {'c':2}
但我希望得到一个答案,为什么第一种方法不起作用,或者我最初的做法是否有问题。
发布于 2022-06-24 11:22:58
对我来说,在DataFrame.at
工作
df.at[pos, 'attributes'] = {'c':2}
print (df)
name attributes
0 a {'c': 2}
https://stackoverflow.com/questions/72742664
复制相似问题