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

2024-05-29 04:30:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于np.where()的问题

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

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

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

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

基本思想是如果df['A']='A',将值A填充到新列fist中, 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

Tags: dfnp分类nanwherenull思想空值
1条回答
网友
1楼 · 发布于 2024-05-29 04:30:32

假设初始df仅为cols 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)或掩蔽数组方法更容易实现

相关问题 更多 >

    热门问题