Python 3.x 基于公式将列添加到数据帧

Python 3.x 基于公式将列添加到数据帧,python-3.x,pandas,Python 3.x,Pandas,我有一个字典,其中JSON值被键入数据框中某列(name)的值,我想向从字典中绘制的数据框中添加一些列 我尝试过这样做: df['district_name'] = data[df['name']]['district_name'] df['district_name'] = df.apply(lambda row:data[row['name']]['district_name']) 但这根本不起作用(它给出了一个“序列不是有效键”,这很有道理;我从来没有完全理解过允许df['col3']

我有一个字典,其中JSON值被键入数据框中某列(
name
)的值,我想向从字典中绘制的数据框中添加一些列

我尝试过这样做:

df['district_name'] = data[df['name']]['district_name']
df['district_name'] = df.apply(lambda row:data[row['name']]['district_name'])
但这根本不起作用(它给出了一个“序列不是有效键”,这很有道理;我从来没有完全理解过允许
df['col3']=df['col1']+df['col2']
起作用的黑魔法)。这里的其他答案让我尝试了以下方法:

df['district_name'] = data[df['name']]['district_name']
df['district_name'] = df.apply(lambda row:data[row['name']]['district_name'])
这给了我
键错误:('name','occurrentedatindex name')


我怎样才能最好地做到这一点呢?

你们很接近了。试试这个:

df['district_name'] = df['name'].map(data.get)['district_name']

你能提供一些测试数据吗?