使用数据帧掩码将值写入新列

2024-09-29 19:22:34 发布

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

基于this solution,我在Pandas数据帧上创建了几个掩码,以创建一个新列,该列应该从不同的列中填充(基于条件)。你知道吗

(简化)代码如下所示:

mask0 = (df['condition'] == 1)
mask1 = (df['condition'] == 0)

df.loc[mask0, 'newColumn'] = df['otherColumn1']
df.loc[mask1, 'newColumn'] = df['otherColumn2']

但是在执行第三行时,我得到以下错误:

ValueError: cannot reindex from a duplicate axis

如果我这么做的话,它会起作用:

df.loc[mask0, 'newColumn'] = 1

我做错什么了?你知道吗


Tags: 数据代码pandasdfthiscondition条件loc
3条回答

您必须在两侧进行过滤:

mask0 = (df['condition'] == 1)
mask1 = (df['condition'] == 0)

df.loc[mask0, 'newColumn'] = df.loc[mask0, 'otherColumn1']
df.loc[mask1, 'newColumn'] = df.loc[mask1, 'otherColumn2']

但是这里最好使用^{}来避免重复代码:

df['newColumn'] = np.select([mask0, mask1], 
                            [df['otherColumn1'], df['otherColumn2']], 
                            default=np.nan)

另一个带有np.where的解决方案:

df['newColumn'] = np.where(df['condition'].eq(1), df['otherColumn1'], df['condition'])
df['newColumn'] = np.where(df['condition'].eq(0), df['otherColumn2'], df['condition'])

您还需要屏蔽“数据提供程序”:

df.loc[mask0, 'newColumn'] = df[mask0, 'otherColumn1']
df.loc[mask1, 'newColumn'] = df[mask1, 'otherColumn2']

如果第一个条件为真,如果后者为假,反之亦然,我们可以使用np.where(..)

df['newColumn'] = np.where(mask0, df['otherColumn0'], df['otherColumn2'])

或者您可以使用np.select(..)以防两者都为假,如果两个条件都为False,则我们可以使用旧值:

df['newColumn'] = np.select(
    [mask0, mask1],
    [df['otherColumn1'], df['otherColumn2']],
    default=df['newColumn']
)

当然,这里我们假设newColumn已经存在于数据帧中(例如通过一些先前的处理)。你知道吗

相关问题 更多 >

    热门问题