如何将 Pandas Dataframe 中某些列的非空值填充到新列中?如何在多个条件下使用 np.where()?

How to fill Non-Null values from some columns in Pandas Dataframe into a new column? How to use np.where() for multiple conditions?

我有一个关于 np.where()

的问题

目前,我有 2 列,每列包含 Null 值和分类值。每列的值是不同的,不会重叠。

现在,我想将这 2 列中的所有非空值应用到新列中,并将新列中的 NaN 值填充为分类值。

我的想法是使用 np.where()

df['C']=np.where(df['A']=='user1', 'user1',(df['B']=='user2','user2','user3'))

基本思路是如果df['A']=='A',将值A填入新列拳头, elif df['B']=='B',也将值 B 填充到新列中, 否则为所有 NaN 值填写值 'C'。

但是,返回语法错误。

ValueError: operands could not be broadcast together with shapes (544,) () (3,) 

感谢您一直以来的帮助!

示例数据:

A   B   C   Desired col C
user1   Null    Null    user1
user1   Null    Null    user1
user1   Null    Null    user1
user1   Null    Null    user1
Null    user2   Null    user2
Null    user2   Null    user2
Null    user2   Null    user2
Null    user2   Null    user2
Null    user2   Null    user2
Null    user2   Null    user2
Null    Null    Null    user3
Null    Null    Null    user3
Null    Null    Null    user3
Null    Null    Null    user3

假设您的初始 df 只有 A、B 和 C 列:

# convert value you don't want to NaNs
df = df.where(df != 'Null')

# temporary list
lst = []

# iterate row-wise
for r in df.iterrows():
    # test if all values in row are the same (1 = no)
    if r[1].nunique() == 1:
        # if different, find the one that is the string and append to list
        a,b,c = r[1] # *this is specific to your example with three cols*
        for i in [a,b,c]:
            if isinstance(i,str):
                lst.append(i)
    else:
        # if same append specified value to list
        lst.append('user3')

df['D'] = lst

它很冗长,对于非常大的 dfs 会有点慢,但它会产生您预期的结果。而且它是可读的。

如果您没有包含所有空值的行会更干净。那么更简洁的单行代码将更可行 df.where()、.apply(lambda) 或掩码数组方法更容易。