Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
list from excel
#1
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)  
Reply
#2
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'
Reply
#3
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
Reply
#4
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])  
Reply
#5
thanks
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Search Excel File with a list of values huzzug 4 1,242 Nov-03-2023, 05:35 PM
Last Post: huzzug
  trouble reading string/module from excel as a list popular_dog 0 424 Oct-04-2023, 01:07 PM
Last Post: popular_dog
  Compare two Excel sheets with Python and list diffenrences dmkfon 1 14,634 Oct-09-2021, 03:30 PM
Last Post: Larz60+
Question How to make a 3D List of Excel Spreadsheets? chatguy 4 2,749 Jan-24-2021, 05:24 AM
Last Post: buran
  Convert Excel to complex list and2handles 1 2,040 Jun-23-2020, 01:51 PM
Last Post: DPaul
  Trying to color an excel row based on list curranjohn46 2 6,563 May-19-2020, 10:35 AM
Last Post: KavyaL
  How to list out specific excel files ajay_pal7 2 2,815 Mar-10-2020, 05:43 AM
Last Post: Larz60+
  Exporting list with dictionary to Excel veromi22 0 3,047 Oct-15-2019, 12:54 AM
Last Post: veromi22
  Is it possible to access and list all macro names in an excel file? kwfine 0 2,451 Feb-07-2018, 04:21 PM
Last Post: kwfine
  Excel Column as List champk 2 10,490 Jan-03-2018, 11:30 PM
Last Post: karaokelove

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020