通过具有列表值的列过滤熊猫

时间:2020-01-30 18:44:31

标签: python pandas dataframe

给出一个熊猫DataFrame,其中包含带有列表值的列

> pd.DataFrame.from_dict(
      {'name' : {0 : 'foo', 1: 'bar', 2: 'baz', 3: 'foz'}, 
       'Attributes': {0: ['x', 'y'], 1: ['y', 'z'], 2: ['x', 'z'], 3: []}
      })

   name    Attributes
0  foo     ['x', 'y']
1  bar     ['y', 'z']
2  baz     ['x', 'z']
3  foz     []

如何仅对那些不包含特定值的行过滤DataFrame,例如'y',在列表中:

2  baz     ['x', 'z']
3  foz     []

预先感谢您的考虑和答复。

2 个答案:

答案 0 :(得分:4)

您可以将一系列列表转换为数据框,并比较所有列是否不等于y

# is they aren't actual list : df['Attributes'] = df['Attributes'].apply(ast.literal_eval)
df[pd.DataFrame(df['Attributes'].tolist()).ne('y').all(1)]

  Name Attributes
2  baz     [x, z]

如果它们不是实际列表:

df[df['Attributes'].str.count('y').eq(0)]

答案 1 :(得分:1)

这应该工作(尽管不是很优雅)

def filter_data_frame(df):
    good_index = []
    for i in range(len(df)):
        if "y" not in df.iloc[i,1]:
            good_index.append(i)

return df.iloc[good_index, :]