Python Forum
list from excel - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: list from excel (/thread-37522.html)



list from excel - devilonline - Jun-22-2022

I
I'm trying to search from a excel file. I've make a convert to a dictionary but still didnt work

I want for example search id 1 and print name Charles
can you help me

table from excel file
[Image: Captura-de-ecr-2022-05-31-133656.png]

import pandas as pd



df = pd.read_excel("book.xlsx")
dict_a = df.to_dict()



search_name = int(input("Provide ID: "))

key_of_value = list(dict_a)[list(dict_a["id"]).index(search_name)]
print(key_of_value)  



RE: list from excel - snippsat - Jun-22-2022

When you frist have gotten data into Pandas,then you use Pandas methods to solve this.
No need to take data out and try to solve this in standard Python.
Example.
import pandas as pd

df = pd.DataFrame(columns = ['Id', 'Name','Age'])
Id = [1, 2, 3]
names = ["Charles", 'Mary', 'Stuart']
ages = [33, 18, 22]
df.Id = Id
df.Name = names
df.Age = ages
>>> df
   Id     Name  Age
0   1  Charles   33
1   2     Mary   18
2   3   Stuart   22
>>> 
>>> df.loc[df['Id'] == 1, 'Name']
0    Charles
Name: Name, dtype: object
Or can use df.query
>>> d = df.query('Id==1')['Name']
>>> d
0    Charles
Name: Name, dtype: object

>>> d.values
array(['Charles'], dtype=object)
>>> d.to_dict()
{0: 'Charles'}
>>> d.to_list()[0]
'Charles'



RE: list from excel - devilonline - Jun-22-2022

but i want that it reads the information from the excel file and the query of example '1' and prints charles
is there a way to do it? thanks


RE: list from excel - snippsat - Jun-22-2022

You don't convert to df.to_dict() this takes it out of Pandas(has a lot of poweršŸ’„) and it standard dictionary.
By the look of your Excels file this should work.
import pandas as pd

df = pd.read_excel("book.xlsx")
df_val = df.query('id==1')['Name']
print(df_val)
print(d.values[0])  



RE: list from excel - devilonline - Jun-22-2022

thanks