我有一个像这样的excel表
ID, Age, Gender, Name
1, 10,1, 'John'
2, 12,0, 'Marry'
3, 20, 1, 'Peter'
请注意,我不能在这里粘贴excel表,所以假设它喜欢上面。鉴于输入是ID,年龄和性别,如何使用python获取名称字段?谢谢例如,id = 2,年龄= 12,性别= 0然后输出是'Marry'。
使用xlrd
从.xls
文件中读取数据并使用pandas
存储数据并选择:
import pandas as pd
from xlrd import open_workbook
#Read datas from .xls file
workbook = open_workbook('data.xls')
sheet = workbook.sheet_by_index(0)
data = []
for row in range(sheet.nrows):
data.append([])
for col in range(sheet.ncols):
value = sheet.cell(row,col).value
if isinstance(value,float):
value = str(int(value))
data[-1].append(value)
#Covert datas to DataFrame with column index
df = pd.DataFrame(data[1:],columns=data[0],dtype=str)
#Input the select values
ID,age,gender = input('Input ID, age and gender splitted by comma.\n').split(',')
#Select the result and output
name = df.loc[(df['ID'] == ID) &
(df['Age'] == age) &
(df['Gender'] == gender)]['Name'].values[0]
print(name)
data.xls
中的数据与您的给定数据一样。
输入:
2,12,0
输出:
结婚