根据单独列中的 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)
然后您可以删除 C1
和 C2
希望对你有帮助~
最佳答案
这比您想象的要简单。希望这可以帮助你!
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/