首页 > 解决方案 > 从熊猫数据框中的系列列表中过滤行

问题描述

在此处输入图像描述

以上是熊猫数据框。
col1 中的值是 col2 中值的键,
例如:在第 3 行中,col1 中的“-4”对应于 col2 中的 list[12,23],类似地
在第 3 行中,col1 中的“-2”对应于 list[ 12] 在 col2 中。

我希望仅过滤掉 col1 中的 +ve 值及其在 col2 中的相应值。

我尝试了多种dict(zip(col1,col2))过滤组合,但没有奏效..

如果有人可以帮助我,那将非常有帮助。

标签: pythonlistpandasdictionaryseries

解决方案


这是一种使用方式pd.DataFrame.apply和生成器理解enumerate

import pandas as pd
from operator import itemgetter

df = pd.DataFrame({'Member': [1, 2, 3],
                   'Col1': [[1, 2, 3], [-1, 2], [-4, -2, 2, 3]],
                   'Col2': [[[12, 23], [12], [4345]],
                            [[12, 23], [12]],
                            [[12, 23], [12], [4345], [34354]]]})

def list_filter(row):
    i = ((i, j) for i, j in enumerate(row['Col1']) if j > 0)
    idx, vals = zip(*i)
    return list(vals), list(itemgetter(*idx)(row['Col2']))

df[['Col1', 'Col2']] = df.apply(list_filter, axis=1).values.tolist()

print(df)

        Col1                      Col2  Member
0  [1, 2, 3]  [[12, 23], [12], [4345]]       1
1        [2]                      [12]       2
2     [2, 3]         [[4345], [34354]]       3

推荐阅读