首页 > 解决方案 > 在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

标签: python

解决方案


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()

推荐阅读