首页 > 解决方案 > 在 Python 中生成多列值的条件语句

问题描述

我正在尝试根据以下数据框中一列“数字”中的条件替换“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 部分,以及“数字”列中的最后一个值不是 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)

标签: pythonpandasdataframe

解决方案


假设您可以安全地覆盖整个列Alloc1Alloc2,您可以np.where按照 Henry Ecker 的建议使用:

df['Alloc1'] = np.where(df['Number'] == 99, 31, 0)
df['Alloc2'] = np.where(df['Number'] == 99, 3, df['Number'] / 2).astype(int)

print(df)
    ID  Number  Alloc1  Alloc2
0  001      99      31       3
1  002      99      31       3
2  003      20       0      10
3  004      40       0      20

推荐阅读