根据其他列的条件创建新列

Creating a new column based on conditions for other columns

我有一个 DataFrame,其列由一些值和 NaN 组成,其中没有为特定列分配值。

import pandas as pd
df = pd.DataFrame({'id': [10, 46, 75, 12, 99, 84],
                   'col1': ['Nan',         
                            15,
                            'Nan',
                            14,
                            'NaN',
                            'NaN'],
                   'col2': ['NaN', 'NaN', 'NaN', 12, 876, 4452],
                   'col3': ['NaN', 11, 13, 546, 9897, 1]
                                   })
                                
df

具有以下输出:

id  col1    col2    col3
0   10  Nan NaN NaN
1   46  15  NaN 11
2   75  Nan NaN 13
3   12  14  12  546
4   99  NaN 876 9897
5   84  NaN 4452  1

我的 objective 是创建一个新列 (col4),它表示 'original' 所有三列 (col1, col2, col3) 都具有 NaN 和 'referenced' 除此以外。 我尝试了 np.where 方法(如下所示),但它不起作用,因为 'NaN'(可能)未被提取为数值。

df['col4'] = np.where((df['col1'] == 'NaN') & (df['col2'] == 'NaN') & (df['col3'] == 'NaN'), 'original', 'referenced')

我在 Python 方面没有那么先进,想不出替代方案应该是什么。

使用 DataFrame.isna for test all columns if missing and then DataFrame.all 测试每行是否全部为真:

#If necessary
import numpy as np

df  = df.replace(['Nan', 'NaN'], np.nan)

df['col4'] = np.where(df[['col1','col2','col3']].isna().all(1), 'original', 'referenced')

你的解决方案Series.isna

df['col4'] = np.where(df['col1'].isna() & df['col2'].isna() & df['col3'].isna(), 
                     'original', 'referenced')

您应该先替换字符串 NaNNan

df = df.replace('(?i)nan', 'NaN', regex=True)
df['col4'] = np.where(df.filter(like='col').eq('NaN').all(axis=1), 'original', 'referenced')

# or

df = df.replace('(?i)nan', pd.NA, regex=True)
df['col4'] = np.where(df.filter(like='col').isna().all(axis=1), 'original', 'referenced')
print(df)

   id col1  col2  col3        col4
0  10  NaN   NaN   NaN    original
1  46   15   NaN    11  referenced
2  75  NaN   NaN    13  referenced
3  12   14    12   546  referenced
4  99  NaN   876  9897  referenced
5  84  NaN  4452     1  referenced