如何在excel中使用python获取某些条件的名称字段?

问题描述 投票:-1回答:1

我有一个像这样的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'。

python excel python-3.x
1个回答
1
投票

使用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

输出:

结婚

© www.soinside.com 2019 - 2024. All rights reserved.