2

熊猫新手在这里。

我正在尝试在我的数据框中创建一个新列,当我将其输入分类器时,它将用作训练标签。

如果给定的 Id 对于 Apples 或 Pears 具有 (Value1 > 0) 或 (Value2 > 0),则标签列的值为 1.0,否则为 0.0。

我的数据框是由 Id 索引的行,如下所示:

Out[30]: 
                Value1                                               Value2  \
    ProductName    7Up     Apple Cheetos     Onion      Pear PopTart    7Up   
    ProductType Drinks Groceries  Snacks Groceries Groceries  Snacks Drinks   
Id                                                                        
100                0.0       1.0     2.0       4.0       0.0     0.0    0.0   
101                3.0       0.0     0.0       0.0       3.0     0.0    4.0   
102                0.0       0.0     0.0       0.0       0.0     2.0    0.0   


    ProductName     Apple Cheetos     Onion      Pear PopTart  
    ProductType Groceries  Snacks Groceries Groceries  Snacks  
Id                                                         
100                   1.0     3.0       3.0       0.0     0.0  
101                   0.0     0.0       0.0       2.0     0.0  
102                   0.0     0.0       0.0       0.0     1.0  

如果熊猫向导可以帮助我了解此操作的语法 - 我的大脑正在努力将它们放在一起。

谢谢!

4

2 回答 2

2

定义你的功能:

def new_column (x):
       if x['Value1'] > 0 :
          return '1.0'
       if x['Value2'] > 0 :
          return '1.0'
       return '0.0'

将其应用于您的数据:

df.apply (lambda x: new_column (x),axis=1)
于 2016-09-02T22:32:02.207 回答
2

@vlad.rad 提供的答案有效,但效率不高,因为 pandas 必须在 Python 中手动循环所有行,无法利用 numpy 矢量化函数加速。以下矢量化解决方案应该更有效:

condition = (df['Value1'] > 0) | (df['Value2'] > 0)
df.loc[condition, 'label'] = 1.
df.loc[~condition, 'label'] = 0.
于 2016-09-03T08:54:00.583 回答