【问题标题】:how to iterate items of list in columns of dataframe如何迭代数据框列中的列表项
【发布时间】:2019-07-05 21:25:20
【问题描述】:

这是我的数据框:

import pandas as pd
df = pd.DataFrame({'animal':['dog','cat','rabbit','pig'],'color':['red','green','blue','purple'],\
               'season':['spring,','summer','fall','winter']})

我有一个清单

l = ['dog','green','purple']

使用这些数据框和列表,我想向 df 添加另一列,如果列“动物”或列“颜色”与 l(list) 的某些项目匹配,这实际上是结果。

所以,我想要的结果(数据框)如下(我想表达一个表格):

pd.DataFrame({'animal':['dog','cat','rabbit','pig'],
               'color':['red','green','blue','purple'],
               'season':['spring,','summer','fall','winter'],
               'tar_rm':[1,1,0,1] })

我必须在列的每一行中迭代列表吗? 我相信 pandas 的优势之一是广播,但我不确定这里是否可能......

【问题讨论】:

    标签: pandas loops conditional-statements


    【解决方案1】:

    用途:

    cols = ['animal','color']
    df['tar_rm'] = df[cols].isin(l).any(axis=1).astype(int)
    print (df)
       animal   color  season  tar_rm
    0     dog     red  spring       1
    1     cat   green  summer       1
    2  rabbit    blue    fall       0
    3     pig  purple  winter       1
    

    详情

    首先比较DataFrame by DataFrame.isin 的过滤列:

    print (df[cols].isin(l))
       animal  color 
    0    True  False  
    1   False   True  
    2   False  False   
    3   False   True  
    

    然后通过DataFrame.any测试每行是否至少有一个True

    print (df[cols].isin(l).any(axis=1))
    0     True
    1     True
    2    False
    3     True
    dtype: bool
    

    最后一次将布尔值转换为整数:

    print (df[cols].isin(l).any(axis=1).astype(int))
    0    1
    1    1
    2    0
    3    1
    dtype: int32
    

    如果性能很重要,请分别比较 isin 每一列,转换为 numpy 数组,按位 OR 链接并最后转换为整数:

    df['tar_rm'] = (df['animal'].isin(l).values | df['color'].isin(l).values).astype(int)
    

    性能:取决于拖链数、匹配行数和列表值数,因此最好在真实数据中测试:

    l = ['dog','green','purple']
    
    df = pd.concat([df] * 100000, ignore_index=True).sample(1)
    In [173]: %timeit df['tar_rm'] = df[['animal','color']].isin(l).any(axis=1).astype(int)
    2.11 ms ± 250 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    In [174]: %timeit df['tar_rm'] = (df['animal'].isin(l).values | df['color'].isin(l).values).astype(int)
    487 µs ± 9.87 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    In [175]: %timeit df['tar_rm'] = np.where(df['animal'].isin(l) | df['color'].isin(l), 1, 0)
    805 µs ± 15.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    

    【讨论】:

      【解决方案2】:

      使用numpy

      df['tar_rm'] = np.where(df['animal'].isin(l) | df['color'].isin(l), 1, 0)
      

      输出

         animal   color   season  tar_rm
      0     dog     red  spring,       1
      1     cat   green   summer       1
      2  rabbit    blue     fall       0
      3     pig  purple   winter       1
      

      【讨论】:

        猜你喜欢
        • 2021-07-10
        • 1970-01-01
        • 1970-01-01
        • 2021-07-20
        • 2021-12-09
        • 1970-01-01
        • 2020-07-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多