【发布时间】:2020-11-14 03:14:02
【问题描述】:
我想在数据框中使用字典键添加一列 这是我尝试的当前代码,但它没有返回行政区而是为所有人返回“其他”
boroughs = {'Manhattan':[1, 2, 3],
'Bronx':[4, 5, 6],
'Brooklyn':[7, 8, 9],
'Staten Island': 10}
def test(x):
for key, value in boroughs.items():
if int(x) in value or int(x) == value:
return key
else:
return 'Other'
df['Boroughs'] = df.precinct.apply(test)
我运行代码后,这是当前的自治市镇
precinct Boroughs
1.0 'Other'
5.0 'Other'
9.0 'Other'
10.0 'Other'
这是预期的结果
precinct Boroughs
1.0 'Manhattan'
5.0 'Bronx'
9.0 'Brooklyn'
10.0 'Staten Island'
我想知道我哪里弄错了提前谢谢
【问题讨论】:
标签: python python-3.x pandas dataframe dictionary