Excel 导入数据集的输入和循环

Input and loops on a excel imported dataset

提问人:Stefy 提问时间:7/31/2023 最后编辑:Stefy 更新时间:7/31/2023 访问量:26

问:

我在 excel 上有一个数据集,我想把它放在 python 上。数据集基本上显示了客户的详细信息,我想要的只是一个工具,通过输入客户名称给我他的号码

数据如下所示:

客户名称 客户编号 客户地址

胡安0055522558街 x, 45 .....

一直在使用 pandas 来清理它,我现在实际上已经将数据集(集合称为 df)放到 python 上,但是我不明白如何正确获取输入消息......

谁能帮我?

谢谢

我想我应该使用一个

choice = input ("enter client name:")
if choice in "client name" == True 
    print("client number is: " ???)

如何让 python 选择我输入的客户端名称的行?

Pandas Loops 对象 输入 数据集

评论


答:

0赞 marinovik 7/31/2023 #1

最好的解决方案是按 过滤数据帧。找到正确的行后,就很容易获得同一筛选行的值。"client name""client number"

使用语句以防数据帧中没有具有此类名称的客户端。try - except

请注意,如果此客户端有多个行,则仅返回在集合中找到的第一个客户端编号。

import pandas as pd

# Load the dataset from the Excel
df = pd.read_excel("clients_data.xlsx")

def get_client_number(input_name):
    try:
        client_number_output = df[df["client name"] == input_name]["client number"].values[0]
        return f"The client number for {input_name} is: {client_number_output}"
    except IndexError:
        return "Client not found."

# Example usage:
client_name_input = input("Enter the client name: ")
print(get_client_number(client_name_input))