[英]Indexing and searching a list of list inside a pandas dataframe
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. 我想要的是当内部列表包含1
时将col
替换为green
,否则将red
替换为col
。 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. 我认为问题在于数据框的每个元素都是一个列表列表。
You can use apply
method; 您可以使用apply
方法; 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
: 另外,您还有一个列表列表列表,可以使用str[0]
提取第一个元素(列表类型),也可以从apply
x
提取它:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.