【问题标题】:how to compare two columns in pandas to make a third column ?如何比较熊猫中的两列以制作第三列?
【发布时间】:2016-08-13 03:41:17
【问题描述】:

我在熊猫数据框中有两列年龄和性别

sex = ['m', 'f' , 'm', 'f', 'f', 'f', 'f']
age = [16 ,  15 , 14 , 9  , 8   , 2   , 56 ]

现在我想提取第三列:像这样 如果年龄9,则输出相应的性别

sex = ['m', 'f'  , 'm','f'    ,'f'    ,'f'    , 'f']
age = [16 ,  15  , 14 , 9     , 8     , 2     , 56 ]
yes = ['m', 'f'  ,'m' ,'child','child','child','f' ]

请帮忙 附言。我还在努力,如果我有任何东西我会立即更新

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用numpy.where:

    df['col3'] = np.where(df['age'] <= 9, 'child', df['sex'])
    

    结果输出:

       age sex   col3
    0   16   m      m
    1   15   f      f
    2   14   m      m
    3    9   f  child
    4    8   f  child
    5    2   f  child
    6   56   f      f
    

    时间安排

    使用以下设置获取更大的示例 DataFrame:

    np.random.seed([3,1415])
    n = 10**5
    df = pd.DataFrame({'sex': np.random.choice(['m', 'f'], size=n), 'age': np.random.randint(0, 100, size=n)})
    

    我得到以下时间:

    %timeit np.where(df['age'] <= 9, 'child', df['sex'])
    1000 loops, best of 3: 1.26 ms per loop
    
    %timeit df['sex'].where(df['age'] > 9, 'child')
    100 loops, best of 3: 3.25 ms per loop
    
    %timeit df.apply(lambda x: 'child' if x['age'] <= 9 else x['sex'], axis=1)
    100 loops, best of 3: 3.92 ms per loop
    

    【讨论】:

    • 这是否像这样工作 np.where(条件,如果这样做,否则这样做)?
    • 是的,这似乎很好用,虽然 df.apply 看起来很直观 :)
    【解决方案2】:

    您可以使用pandas.DataFrame.where。例如

    child.where(age<=9, sex)
    

    【讨论】:

    • 这里的语法不正确。如果你想使用DataFrame.where,它应该是这样的:df['sex'].where(df['age'] &gt; 9, 'child')。
    【解决方案3】:
    df = pd.DataFrame({'sex':['m', 'f' , 'm', 'f', 'f', 'f', 'f'],
        'age':[16, 15, 14, 9, 8, 2, 56]})
    df['yes'] = df.apply(lambda x: 'child' if x['age'] <= 9 else x['sex'], axis=1)
    

    结果:

       age sex    yes
    0   16   m      m
    1   15   f      f
    2   14   m      m
    3    9   f  child
    4    8   f  child
    5    2   f  child
    6   56   f      f
    

    【讨论】:

      猜你喜欢
      • 2022-08-19
      • 1970-01-01
      • 2015-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-31
      • 2017-12-14
      相关资源
      最近更新 更多