【问题标题】:To filter rows from a list in a series in a dataframe in pandas从熊猫数据框中的系列列表中过滤行
【发布时间】:2018-11-24 10:53:13
【问题描述】:

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

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

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

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

【问题讨论】:

  • 欢迎来到 SO。请阅读how-tomcve 然后通过df.to_dict() 分享您的数据框代码,以便我们重现它。

标签: python list pandas dictionary series


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    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]] 
    

    【讨论】:

    • 谢谢@msolomon87
    猜你喜欢
    • 2017-12-15
    • 2021-12-01
    • 2019-05-21
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多