python - 在 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)
解决方案
假设您可以安全地覆盖整个列Alloc1
和Alloc2
,您可以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
推荐阅读
- javascript - 更改下拉列表中的值属性名称并使其起作用?
- powerbi - 在 Power BI X 轴标签中,如何仅显示周开始日而不是所有日期系列?
- jquery - 删除表格编辑js中的行后表格行没有被删除
- oracle - 如何使用 Bat 文件执行 oracle 的 dbms_stats
- ros - 加载共享库时出错:libpangolin.so:无法打开共享对象文件:没有这样的文件或目录
- r - R中连接列的条件连接
- javascript - 如何在 type='number' 的输入字段中允许 1.00
- java - 如果它在java中有无限嵌套,我如何遍历深度嵌套的JSON?
- javascript - 以 UTC 格式反应排序日期 (e:2019-11-14T10:18:51Z)
- android - 如何使用 LiveData 从 Room 数据库更新文本视图?