jok*_*kol 5 python numpy dataframe pandas
基于单独列中的 nan 值创建新列的最有效方法是什么(考虑到数据帧非常大)在 OTW 中,如果任何列NaN在其中一行中有 ,则新列的相应值应该是1
注意:列的数据类型可能是不同的对象,而不仅仅是整数/浮点数
X A B
1 2 3
4 NaN 1
7 8 9
3 2 NaN
5 NaN 2
Run Code Online (Sandbox Code Playgroud)
应该给
X A B C
1 2 3 0
4 NaN 1 1
7 8 9 0
3 2 NaN 1
5 NaN 2 1
Run Code Online (Sandbox Code Playgroud)
尝试过的代码(感谢一些在线帮助):
df['C'] = np.where(np.any(np.isnan(df[['A', 'B']])), 1, 0)
Run Code Online (Sandbox Code Playgroud)
但它会引发以下错误
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''
Run Code Online (Sandbox Code Playgroud)
这会返回一个空数据帧(因为 A 列和 B 列在一行中永远不会有 NaN 值
df['C'] = np.where(np.any(pd.isnull(df[['A', 'B']])), 1, 0)
Run Code Online (Sandbox Code Playgroud)
找到了解决方法:
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)
Run Code Online (Sandbox Code Playgroud)
然后你可以放下C1并C2
希望这有帮助~
这比你想象的简单。希望这可以帮助您!
df['C'] = df.isna().sum(axis=1).apply(lambda x: 0 if x==0 else 1)
Run Code Online (Sandbox Code Playgroud)