python - 在python中根据多个条件创建列
问题描述
我想创建一个新列 - “结果”,并且该列中的值将根据以下条件存储。我的条件是——
1-col emp 是 'salied' 或 'business' & col inc 是 '> 1000k' & col flg 是 'stp' 然后添加一个值为 'no_issue' 的列结果
2-col emp 是 'salied' 或 'business' & col inc '<= 1000k' & col flg 是 'n_stp' 然后将 'no_issue' 放入结果中
3-col emp 是 'salied' 或 'business' & col inc '> 100kh' & col flg is 'n_stp' 然后将 'issue' 放入结果中
4-col emp 是 'salied' 或 'business' & col inc '<= 1000k' & col flg 是 'stp' 然后将 'issue' 放入结果中
5-col emp 是 'other' & col flg 是 'n_stp' 然后在结果中输入 'no issue'
6-col emp 是 'other' & col flg 是 'stp' 然后把 'issue' 放在结果中
这是一个非常复杂的逻辑,请帮助我获得所需的输出
我添加列的最终数据看起来像 -
import pandas as pd
data = [['1', 'stp', 'salaried', '> 10 lakh', 'no_issue'],
['2', 'stp', 'business', '> 10 lakh', 'no_issue' ],
['3', 'n_stp', 'salaried', '<= 10 lakh', 'no_issue']]
df= pd.DataFrame(data, columns = ['s.no', 'flg', 'emp', 'inc', 'result'])
df
s.no flg emp inc result
1 stp salaried > 10 lakh no_issue
2 stp business > 10 lakh no_issue
3 n_stp salaried <= 10 lakh no_issue
解决方案
import openpyxl
path= r"c:\ path of file"
work_book=openpyxl.load_workbook(path)
sheet=work_book.active
rows=sheet.max_row
columns=sheet.max_column
sheet.cell(1,columns+1).value="Result"
for i in range(2,rows):
if (sheet.cell(i,1).value in ('salaried' , 'business') ) and (int(sheet.cell(i,3).value)>1000000) and (sheet.cell(i,4).value=='stp'):
sheet.cell(i,5).value='no issue'
elif #another conditions here:
#do something
elif # another conditions here:
# do something
work_book.save(path)
work_book.close()
推荐阅读
- sql - 在循环中插入来自不同表的 UNION ALL 记录?
- regex - 保护转义字符免受模式结尾的影响
- c - 在c中创建文件没有重复
- c# - 取消合并excel行和重复数据c#
- excel - VBA 在工作表之间复制和粘贴
- wordpress - is_home() 类似 WordPress 自定义帖子类型的函数
- flutter - 如何为共享相同状态类的两个小部件使用两个全局键
- python - 是否可以在 tensorflow tf.function 中测试张量大小?
- angular - 在 ngSwitch 中开启延迟加载
- python - 你能创建一个从买家和卖家列中找到净数量的函数吗?