程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Pandas realizes if function of Excel

編輯:Python

1. Raw data

 2. Original column change

Listing and original listing identical Is modification

import pandas as pd
import numpy as np
df = pd.read_excel('test.xlsx')
df[' Gender '] = np.where(df[' Gender '] == 1,' male ',' Woman ')# amount to IF(F2=1,' male ',' Woman ')
df.to_excel('test02.xlsx',index=False)

 3. New column

Listing and original listing inequality Is new

import pandas as pd
import numpy as np
df = pd.read_excel('test.xlsx')
df[' Gender 2'] = np.where(df[' Gender '] == 1,' male ',' Woman ')# amount to IF(F2=1,' male ',' Woman ')
df.to_excel('test02.xlsx',index=False)

 4. Create a new column at the specified position

Ideas : First new , List again

insert(loc, column, value, allow_duplicates=False)

Where is the :

loc: Insert the index of the column . The first column is 0.
column: Give the new column a name .
value: Array of values for the new column .
allow_duplicates: Whether to allow new column names to match existing column names . The default is false .

import pandas as pd
import numpy as np
df = pd.read_excel('test.xlsx')
df.insert(1, ' Gender 2', "") # Location , listed , data
df[' Gender 2'] = np.where(df[' Gender '] == 1, ' male ', ' Woman ') # amount to IF(F2=1,' male ',' Woman ')
df.to_excel('test02.xlsx', index=False)

 

5. Advanced (if nesting )

import pandas as pd
import numpy as np
df = pd.read_excel('test.xlsx')
# IF(F2=1,IF(B2>90,' yes ',' no '),' no ')
df[' Whether to go to the office '] = np.where(df[' Gender '] == 1, np.where(df[' mathematics '] > 90, ' yes ', ' no '), ' no ')
df.to_excel('test02.xlsx', index=False)


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved