首页 > 解决方案 > 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'

我知道我的方法有缺陷;任何帮助表示赞赏。

标签: pythonpandas

解决方案


试试这个:

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

只需locisin.

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

推荐阅读