Home > database >  Reading excel values in python from user input
Reading excel values in python from user input

Time:10-15

I'm new to this community and I'm currently learning Python. For my first little project, I want to ask the user for input (An element from the periodic table) and print the corresponding properties such as name, number and mass.

import pandas as pd
df = pd.read_excel(r'path\excelfile.xlsx')
    
Symbol = input('Input Symbol: ')

try:
    value = df.index[df['Symbol']== Symbol].tolist()[0]
    print(f'properties of {Symbol} are: ')
    print("Element Name: ",df['Atomic_name'][value])
    print("Element Number : ",df['Atomic_number'][value])
    print("Element Mass  : ",df['Atomic_weight'][value], "g/mol")
except IndexError:
    print('Symbol not found')

For the excel file, I'm using the following file: [https://easyupload.io/qrl7yu][1]

Frankly, it works for the first symbol only if your input is 'H' resulting in the following output:

Input Symbol: H
properties of H are:
Element Name  :  Hydrogen
Element Number:  1
Element Mass  :  1.01 g/mol

This is exactly what I want but when I try a symbol from the same column 'Symbol', it won't work. I want to have it work for all the symbols. How do I define that all the symbols for the input are from the same column? I think it has something to do with the 7th line where I define value =.

Wixxix [1]: https://easyupload.io/qrl7yu

CodePudding user response:

Maybe this works for you:

import pandas as pd

df = pd.read_excel('LoCE.xlsx')

user_input = input('Input Symbol: ')

mask = df.loc[:, 'Symbol'] == user_input

df_mask = df.loc[mask, :]

print(df_mask)

CodePudding user response:

If you change the Symbol column to str type, then query using df.str.contains it works:

df['Symbol']=df['Symbol'].astype(str)
df[df['Symbol'].str.contains("Li")]

CodePudding user response:

I think your code is working fine, the problem is with the symbols data containing extra spaces. You can use trim() function on excel first to clean the empty spaces and then retry your code.

For example you will see below the space between the quotes and Cr That's causing a mismatch between your data and the input from the user ' Cr'

  • Related