python - Python:如果列 Y 的值在可能值的列表 L 中,则更新列 X 值
问题描述
有一个包含巴士站 ID 列表的数据框,并且集线器为“无”。我需要更新数据框 - 如果公交车站 ID 在列表 a_ids 中,则其对应的集线器应该是 a,如果在 b_ids 中,则集线器 = b 等等。
a = pd.DataFrame(({'stop' : ['10388','10382','10383','10387','10389','25568'],'hub' : ['none', 'none', 'none', 'none', 'none', 'none']}))
a_ids = ['10388','10382','10383']
b_ids = ['10387','10389','25568','10381']
a
我试过了:
a[(a.stop.isin(a_ids)),'hub'] = 'a'
我知道我的方法有缺陷;任何帮助表示赞赏。
解决方案
试试这个:
a = pd.DataFrame(({'stop' : ['10388','10382','10383','10387','10389','25568'],
'hub' : ['none', 'none', 'none', 'none', 'none', 'none']}))
a_ids = ['10388','10382','10383']
b_ids = ['10387','10389','25568','10381']
print (a)
# Output
stop hub
0 10388 none
1 10382 none
2 10383 none
3 10387 none
4 10389 none
5 25568 none
只需loc
与isin
.
a.loc[a.stop.isin(a_ids), 'hub'] = 'a'
a.loc[a.stop.isin(b_ids), 'hub'] = 'b'
output:
stop hub
0 10388 a
1 10382 a
2 10383 a
3 10387 b
4 10389 b
5 25568 b
推荐阅读
- javascript - 承诺返回 null
- lua - lua 中的 C# 中的“goto”循环是否有等价物?(必须兼容Love2D)
- build - QBS:qbs.buildVariant 和 qbs.configurationName 有什么区别?
- php - codeigniter 保存任何事务
- ruby-on-rails - Rails 5 设计不保存嵌套属性
- python-3.x - 使用 matplotlib 选择网格覆盖的坐标系
- javascript - 如何根据类别对产品进行排序
- sockets - 如何关闭等待服务器套接字侦听的任务?
- bitmap - 如何在文件中存储不同的位长度?
- python - 使用另一个列表中的键聚合一个列表