我有一个这样的 excel 表格
ID, Age, Gender, Name
1, 10,1, 'John'
2, 12,0, 'Marry'
3, 20, 1, 'Peter'
请注意,我无法在此处粘贴 excel 表,因此假设它喜欢上面。给定输入是 ID、年龄和性别,如何使用 python 获取名称字段?谢谢例如,id=2,年龄=12,性别=0,则输出为"已婚"。
使用 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
输出:
嫁