python - 根据其他列中的 'NaN' 值在 Pandas Dataframe 中创建一个新列

标签 python pandas numpy dataframe

根据单独列中的 nan 值创建新列的最有效方法是什么(考虑到数据框非常大) 在 OTW 中,如果任何列的其中一行中有 NaN,则新列的对应值应为 1

Note: The dtypes of the column may be different objects, not just integers/floats

X A   B
1 2   3    
4 NaN 1    
7 8   9    
3 2   NaN  
5 NaN 2   

应该给

X A   B    C
1 2   3    0
4 NaN 1    1
7 8   9    0
3 2   NaN  1
5 NaN 2    1

代码尝试(感谢一些在线帮助):

df['C'] = np.where(np.any(np.isnan(df[['A', 'B']])), 1, 0)

但它抛出以下错误

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

这将返回一个空数据框(因为 A 和 B 列都不会在一行中包含 NaN 值

df['C'] = np.where(np.any(pd.isnull(df[['A', 'B']])), 1, 0)

Found a Workaround :

df['C1'] = np.where(np.isnan(df['A'].values), 1, 0) 
df['C2'] = np.where(np.isnan(df['B'].values), 1, 0)
df['C'] = df[['C1','C2']].max(axis=1)

然后您可以删除 C1C2

希望对你有帮助~

最佳答案

这比您想象的要简单。希望这可以帮助你!

df['C'] = df.isna().sum(axis=1).apply(lambda x: 0 if x==0 else 1)

关于python - 根据其他列中的 'NaN' 值在 Pandas Dataframe 中创建一个新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59043662/

相关文章:

python - 如何将图像保存到磁盘

javascript - Python 相当于 JavaScript 的 `Object.defineProperty()`

python - 向量化 pandas.DataFrame 的整合

python - 如何使用 python 读取 edf.event 文件?

python - 在多处理进程之间共享大型只读 Numpy 数组

python - 同一个单词出现 KeyError

python - 从列表中删除空元素

python - 如何将 json 格式的特定值检索到 pandas dataframe 列中

python - 如果前 x 行值相同,如何删除 Pandas 数据框中的相同列?

python - 如何引用 numpy 数组对象?