如果列中的值为NaN,则创建标签不完整的新列

时间:2018-08-23 15:37:13

标签: python python-3.x pandas

我有这个数据框。

using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(keySize))
      {
        privateKey = RSA.ToXmlString(true);
      }

我正在尝试通过检查列“ a”中的值类型并相应地分配新标签来创建新列。结果应如下所示:

     a  b
0  NaN  2
1  2.0  4
2  NaN  7

代码是:

     a  b  c
0  NaN  2  incomplete
1  2.0  4  complete
2  NaN  7  incomplete

我正在尝试使用简单的if / else语句,但出现此错误:

if data_frame['a'].isna() == True: 
   data_frame['c'] = 'incomplete'
else:
   data_frame['c'] = 'complete'

有人可以提出解决方案吗?

非常感谢

3 个答案:

答案 0 :(得分:4)

我建议使用np.where,尽管这需要额外导入

df['c'] = np.where(df.a.notnull(), 'complete', 'incomplete')

答案 1 :(得分:2)

您可以只使用add_shortcode( 'all_state_list_shortcode', 'all_state_list_function' ); function all_state_list_function(){ if ( isset($_GET['sku']) && ! empty($_GET['sku']) ) { ob_start(); $sku = esc_attr( $_GET['sku'] ) .'%'; global $wpdb; $results = $wpdb->get_col( " SELECT p.ID FROM {$wpdb->prefix}posts as p JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id WHERE p.post_type LIKE 'product' AND p.post_status LIKE 'publish' AND meta_key LIKE '_sku' AND meta_value LIKE '$sku' " ); if( count($results) > 0 ) { echo implode(',', $results); } else { echo 'Nothing found'; } return ob_get_clean(); } }

Series.apply

输出

df['c'] = df['a'].apply(lambda x: 'complete' if not np.isnan(x) else 'incomplete')

时间:

     a  b           c
0  NaN  2  incomplete
1  2.0  4    complete
2  NaN  7  incomplete

似乎最好的性能解决方案是np.where(+1 @roganjosh)

答案 2 :(得分:1)

我认为您不需要在此处循环

df['a'].notnull().map({True:'complete',False:'incomplete'})
Out[347]: 
0      complete
1    incomplete
2      complete
dtype: object