dirpath = os.path.dirname(os.path.abspath(file)) filepath = os.path.join(dirpath,…
- User
dir_path = os.path.dirname(os.path.abspath(file)) file_path = os.path.join(dir_path, 'excel.xlsx') data = pd.DataFrame() with pd.ExcelFile(file_path) as xlsx: for sheet_name in xlsx.sheet_names: df = pd.read_excel(xlsx, sheet_name=sheet_name) data = data.append(df, ignore_index=True)
data.append has error
- Assistant
Without knowing the exact error message, it's difficult to determine the exact issue with
data.append. However, a possible issue could be that theignore_indexparameter is set toTrue, but the data frames being appended do not have the same columns. This can causedata.appendto fail because it tries to align the columns and there are mismatched columns.To fix this, you could either ensure that all sheets in the Excel file have the same columns, or you could set
ignore_indextoFalseso that the original index of each data frame is preserved and no column alignment is attempted. - User
AttributeError: 'DataFrame' object has no attribute 'append'
- Assistant
This error message suggests that
datais already aDataFrameobject and does not have an attribute calledappend.In this case, try using the
pd.concat()function instead ofdata.append().Here's an example of how you can modify your code using
pd.concat():codedir_path = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.join(dir_path, 'excel.xlsx') data_frames = [] with pd.ExcelFile(file_path) as xlsx: for sheet_name in xlsx.sheet_names: df = pd.read_excel(xlsx, sheet_name=sheet_name) data_frames.append(df) data = pd.concat(data_frames, ignore_index=True)This creates an empty list called
data_framesand appends each data frame to the list. Then, thepd.concat()function is used to concatenate all the data frames together into oneDataFrameobject calleddata. Theignore_indexparameter is set toTrueto create a new index for the concatenated data. - User
ValueError: [TypeError("'numpy.int64' object is not iterable"), TypeError('vars() argument must have dict attribute')]
- Assistant
This error is related to attempting to apply an invalid operation to a NumPy
int64object. It's possible that the error is occurring whenpd.read_excel()is trying to convert data from one of your Excel sheets into aDataFrame, and it encounters a cell with an invalid data type.You can try to isolate the sheet that is causing the error by adding a
try-exceptblock around thepd.read_excel()statement to catch and print the stack trace of any errors that occur.Here's an example of how to do that:
codedir_path = os.path.dirname(os.path.abspath(__file__)) file_path = os.path.join(dir_path, 'excel.xlsx') data = pd.DataFrame() with pd.ExcelFile(file_path) as xlsx: for sheet_name in xlsx.sheet_names: try: df = pd.read_excel(xlsx, sheet_name=sheet_name) data = data.append(df, ignore_index=True) except Exception as e: print(f"Error reading '{sheet_name}': {e}")