Home > Back-end >  How can I print the cell name of a dataframe from an Excel file in Python Pandas?
How can I print the cell name of a dataframe from an Excel file in Python Pandas?

Time:04-07

For example: I have a wrong value from the base Excel file (a cell), how can I print "Error in cell C7" in Python? I think I first need to get the index of the cell of the dataframe but then what? My boss is gonna use wrong values (for testing) from the base Excel file that I'll use with the dataframe. I was thinking of making a dictionary of indexes of Pandas and Excel but I don't really know how to do that. Thanks.

CodePudding user response:

Can be achieved by iterating on the data frame with try-catch statements

df = pd.DataFrame({'name':['john', 'joe'], 'age':['20', np.nan]})

col_dict = {df.columns[i]:chr(i 65) for i in range(len(df.columns))}
for i, item in enumerate(df):
    try:
        df.loc[i, 'age'] = int(df.loc[i, 'age'])
    except ValueError:
        print('ERROR at cell: {} - index {}: column: {!r}'.format(col_dict[item] str(i), i, item))

CodePudding user response:

Try and use conditions for checking if the cell is empty. Also include the try catch statement to catch the Exceptions as shown in below example.

import pandas
from os import sep

inputdir = "data"
fname = "sample.csv"

try:
    filename = inputdir   sep   fname
    data = pandas.read_csv(filename)
    if (not data.empty):
       print(data.iloc[0, 0])

except OSError as e:
    print("ERROR: Unable to find or access file:", e)
    pass


  • Related