第三列基于前两列

Third column based on first two columns

我有一个数据框,其中包含两列,分别是数量和价格。我想根据上述列创建第三列。

如果体积数量和体积价格列都有值,或者两者都是空白或空的,那么第三列应该有值“是”。 如果其中一列作为值而另一列为空或空白,那么我希望第三列的值应为“NO” 例如

     volume qty  volume price   column x
        20            100          YES 
                                   YES
        30                         NO
                      200          NO   

有什么办法可以用任何内置函数实现这个。

您可以使用 numpy.select:

情况 1:当列具有空 (NaN) 值时:

In [152]: df
Out[152]: 
   volume qty  volume price
0        20.0         100.0
1         NaN           NaN
2        30.0           NaN
3         NaN         200.0

In [152]: import numpy as np

In [153]: conds = [df['volume qty'].notna() & df['volume price'].notna(), df['volume qty'].isna() & df['volume price'].isna(), df['volume qty'].isna() | df['volume price'].isna()]

In [154]: choices = ['YES', 'YES', 'NO']

In [156]: df['column x'] = np.select(conds, choices)

In [157]: df
Out[157]: 
   volume qty  volume price column x
0        20.0         100.0      YES
1         NaN           NaN      YES
2        30.0           NaN       NO
3         NaN         200.0       NO

情况2:当列有空值时:

In [167]: df
Out[167]: 
  volume qty volume price
0         20          100
1                        
2         30             
3                     200

In [164]: conds = [~df['volume qty'].eq('') & ~df['volume price'].eq(''), df['volume qty'].eq('') & df['volume price'].eq(''), df['volume qty'].eq('') | df['volume price'].eq('')]

In [165]: choices = ['YES', 'YES', 'NO']

In [168]: df['column x'] = np.select(conds, choices)

In [169]: df
Out[169]: 
  volume qty volume price column x
0         20          100      YES
1                              YES
2         30                    NO
3                     200       NO