我试图根据下面数据框中一列“Number”中的条件替换列“Alloc1”和“Alloc2”中的值
data = {'ID': ['001', '002', '003', '004'], 'Number': [99, 99, 20, 40], 'Alloc1': [np.NaN, np.NaN, np.NaN, np.NaN], 'Alloc2': [np.NaN, np.NaN, np.NaN, np.NaN]}
# Create DataFrame.
df = pd.DataFrame(data)
我根据条件插入值的代码如下:-
for numbers in df["Number"]:
if (numbers == 99):
df["Alloc1"] = 31
df["Alloc2"] = 3
else:
df["Alloc1"] = 0
df["Alloc2"] = numbers/2
上面的语句似乎只执行语句的else部分,并执行“Number”列中不是99的最后一个值。我怎样才能解决这个问题?功能会很好。理想输出应为:-
final = {'ID': ['001', '002', '003', '004'], 'Number': [99, 99, 20, 40], 'Alloc1': [31, 31, 0, 0], 'Alloc2': [3, 3, 10, 20]}
# Create DataFrame.
final_df = pd.DataFrame(final)
尝试使用矢量化操作来处理此问题
假设您可以安全地覆盖整个列
Alloc1
和Alloc2
,您可以按照Henry Ecker的建议使用np.where
:我认为“矢量化”解决方案的性能会比这个更好,而且无论是那个版本还是
where
版本都更“优秀”。这个答案只是向你展示如何使用更像你所遵循的方法来实现你想要的。这不是一个非常“熊猫”式的做事方式,但可能有助于理解为什么你尝试的东西不起作用产出:
相关问题 更多 >
编程相关推荐