Reputation: 5263
Let say we have a list of lists like this:
lst = [[[[1,2]]],[[[2,3]]],[[[3,4]]]]
and then we make a panda data frame here:
import pandas as pd
import numpy as np
df = pd.DataFrame(lst, columns = ['col'])
print df
and returns
col
0 [[1, 2]]
1 [[2, 3]]
2 [[3, 4]]
what I want is replacing col
with green
when the interior list includes 1
and red
if not. I tried this:
df['col'] = np.where(1 in df['col'], 'green', 'red')
print df
but does not return correct answer!!!
col
0 green
1 green
2 green
I think the problem is that each element of data frame is a list of lists.
Upvotes: 0
Views: 944
Reputation: 214957
You can use apply
method; Also you have a list of list of list, you can either use str[0]
to extract the first element (of list type) out or you can extract it from x
in apply
:
df['col'].str[0].apply(lambda x: 'green' if 1 in x else 'red')
#0 green
#1 red
#2 red
#Name: col, dtype: object
Another option:
df['col'].apply(lambda x: 'green' if 1 in x[0] else 'red')
#0 green
#1 red
#2 red
#Name: col, dtype: object
Upvotes: 1