python - If value in dataframe row = list (not in order), change another row value to 'ONLINE'
问题描述
import numpy as np
import pandas as pd
list1=pd.DataFrame({'A':['a','b','c','d','x'],'B':['a','b','c','d','x']})
list2=[['1','b','c','a']]
list3=['a','b','c','d','e']
list1
A B
0 a a
1 b b
2 c c
3 d d
4 x x
i get a value error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
When I do replace list1.B using list3: it works.
for i in range(len(list1.A)):
if list1.A[i] in list3:
list1.B[i]='ONLINE'
list1
A B
0 a ONLINE
1 b ONLINE
2 c ONLINE
3 d ONLINE
4 x x
How do I do for list2? Thanks I tried query and isin too doesn't work.
解决方案
利用:
#change DataFrame to df for distingush between lists and df
df=pd.DataFrame({'A':['a','b','c','d','x'],'B':['a','b','c','d','x']})
list2=[['1','b','c','a']]
list3=['a','b','c','d','e']
我认为这里最好使用Series.isin
for DataFrame.loc
select column by mask:
df.loc[df['B'].isin(list3), 'B'] = 'ONLINE'
对于第二个列表是嵌套的,所以选择第一个:
print (list2[0])
['1', 'b', 'c', 'a']
df.loc[df['B'].isin(list2[0]), 'B'] = 'ONLINE'
print (df)
A B
0 a ONLINE
1 b ONLINE
2 c ONLINE
3 d d
4 x x
如果有多个嵌套列表,请使用展平列表:
list4=[['1','b'],['c','a']]
print ([y for x in list4 for y in x])
df.loc[df['B'].isin([y for x in list4 for y in x]), 'B'] = 'ONLINE'
print (df)
A B
0 a ONLINE
1 b ONLINE
2 c ONLINE
3 d d
4 x x
推荐阅读
- python-3.x - Python - any() - 检查列表中的元素是否为
- http - 如何在 kotlin 中使用 mockk 和 fuel 模拟 POST 请求?
- excel - 循环遍历不同大小的数据行并返回 MAX 值所需的 VBA 代码
- android - 如何使用phonegap截屏并在手机中分享
- javascript - List.innerHTML,为什么需要它(javascript)
- php - 从 WooCommerce 中删除所需的变化价格
- python - PyTorch next(iter(training_loader)) 极慢,简单数据,不能num_workers?
- javascript - 如何将锚链接列表转换为选择下拉菜单,该下拉菜单在选项更改时操作更改选项卡?
- cordova - Fork 插件 Ionic
- javascript - HTML 表格 - Javascript 选择和取消选择元素(单元格)