简体   繁体   English

将条件应用于两个熊猫数据框列

[英]Apply conditional on two pandas dataframe columns

I have this dataframe: 我有这个数据框:

在此处输入图片说明

I want to create a ZIP column which will get the value of ZIP_y when ZIP_x is NaN and the value of ZIP_x when ZIP_x is not NaN. 我想创建一个ZIP列,当ZIP_x为NaN时将获得ZIP_y的值,而当ZIP_x不是NaN时将获得ZIP_x的值。

I tried this code: 我尝试了这段代码:

dm["ZIP"]=numpy.where(dm["ZIP_x"] is numpy.nan, dm["ZIP_y"],dm["ZIP_x"])

But that gave me this output: 但这给了我以下输出:

在此处输入图片说明

As you can see, the ZIP column seems to be getting the values of ZIP_x in each of its cells. 如您所见,ZIP列似乎正在获取其每个单元格中的ZIP_x值。

Do you know how to achieve what I am after? 你知道如何实现我的追求吗?

You want this: 你要这个:

dm["ZIP"]=numpy.where(dm["ZIP_x"].isnull(), dm["ZIP_y"],dm["ZIP_x"])

You can't use is or == for that matter to compare NaN s 您不能使用is==来比较NaN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM