首页 > 解决方案 > 在 pandas 数据框中,给定两个列表列,根据第二列中的值访问第一列的值

问题描述

我有带有两个列表列的 Pandas 数据框:

   df = 
           a                          label
        [1, 2, 4, 5]                    [0, 0, 1, 0]
        [100, 12, 23, 4]                [1, 0, 0, 1]

最终,我想形成一个新的 column a_positive,它也是一个包含所有元素的列表afor ,label所以1

 df_output =
         a                                  label                a_positive            
        [1, 2, 4, 5]                    [0, 0, 1, 0]              [4]
        [100, 12, 23, 4]                [1, 0, 0, 1]              [100, 4]

是否可以一起使用applyziping 列表?

标签: python-3.xpandas

解决方案


尝试

df['new']=df.apply( lambda x : [s  for s, t in zip(x['a'],x['label']) if t==1],axis=1)
df
Out[78]: 
                  a         label       new
0      [1, 2, 4, 5]  [0, 0, 1, 0]       [4]
1  [100, 12, 23, 4]  [1, 0, 0, 1]  [100, 4]

推荐阅读