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

标签: pythonpandas

解决方案


利用:

#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.isinfor DataFrame.locselect 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

推荐阅读