Python使用where条件更新多个列。错误无法一起广播

时间:2017-04-25 17:33:46

标签: python pandas numpy where

我需要根据条件更新DB中的几个列。我正在使用numpy.where而宁愿不改变它。

这是我能做的:

DB['Start'] = np.where(((DB['Start Date']<=time_delta) | (DB['Start Date'].isnull()) | (DB['Start Date'] == "")),DB['Start'],DB['Start Date'])

DB['End'] = np.where(((DB['Start Date']<=time_delta) | (DB['Start Date'].isnull()) | (DB['Start Date'] == "")),DB['End'],DB['End Date'])

以及其他5列的等等......但这不会在计算上有效。

拥有这样的东西会很高兴:

DB[['Start','End']] = np.where(((DB['Start Date']<=time_delta) | (DB['Start Date'].isnull()) | (DB['Start Date'] == "")),DB[['Start','End']],DB[['Start Date','End Date']])

但它不起作用并给出以下错误信息:&#34;操作数不能与形状(10,)(10,2)(10,2)和#34;一起广播。

您是否有任何建议如何根据numpy.where条件有效更新多列?

1 个答案:

答案 0 :(得分:0)

不确定这是否可以接受,因为您提到了计算效率,这需要与手动列出更新步骤相同的计算机时间。但万一它有用...

columns_to_filter = ['Start', 'End']

for c in columns_to_filter:
    DB[c] = np.where(((DB['Start Date']<=time_delta) | (DB['Start Date'].isnull()) | (DB['Start Date'] == "")),DB[c],DB[c + ' Date'])