繁体   English   中英

从熊猫的数据框中的一系列列表中筛选行

[英]To filter rows from a list in a series in a dataframe in pandas

在此处输入图片说明

上面是一个熊猫数据框。
col1中的值是col2中值的键排序
例如:在第3行中,col1中的“ -4”对应于col2中的list [12,23]
在第3行中,col1中的“ -2”对应于col2中的list [12]。

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

我尝试了dict(zip(col1,col2))多种组合进行过滤,但是没有用。

如果有人可以帮助我,那将真的很有帮助。

这是使用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

这是一个使用几个循环的选项

row2=[]
col2=[]
row1=[]
col1=[]
for i in range(0,len(df.Col1)):
    for j in range(0,len(df.Col1.tolist()[i])):
        if df.Col1.tolist()[i][j] > 0:
            print i
            print j
            row2.append(df.Col2.tolist()[i][j])
            row1.append(df.Col1.tolist()[i][j])
    col1.append(row1)
    col2.append(row2)
    row1=[]
    row2=[]

df['Col1']=col1
df['Col2']=col2

print(df)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM