基于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
我做错什么了?你知道吗
您必须在两侧进行过滤:
但是这里最好使用^{} 来避免重复代码:
另一个带有
np.where
的解决方案:您还需要屏蔽“数据提供程序”:
如果第一个条件为真,如果后者为假,反之亦然,我们可以使用
np.where(..)
:或者您可以使用
np.select(..)
以防两者都为假,如果两个条件都为False
,则我们可以使用旧值:当然,这里我们假设
newColumn
已经存在于数据帧中(例如通过一些先前的处理)。你知道吗相关问题 更多 >
编程相关推荐