'How to deal with the ValueError and KeyError in Excelwriter and Pandas Dataframe

I'm running a code as below through excelwriter with different periods ie months, some months the number of rows to my DataFrame is 29,28,or 30, but when the numbers exceeds 30 I get the error below.

could any assist on the way out.

Thanks a lot in advance

Traceback (most recent call last): File "C:\Users\Ben\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\indexes\range.py", line 385, in get_loc return self._range.index(new_key) ValueError: 31 is not in range

The above exception was the direct cause of the following exception:

Traceback (most recent call last): File "C:\Users\Ben\PycharmProjects\Financials Automation\Financials.py", line 3174, in main() File "C:\Users\Ben\PycharmProjects\Financials Automation\Financials.py", line 2960, in main worksheet1.merge_range(x[0], 0, x[-1], 0, lev10_Pnlf.loc[x[0], 'Category'], merge_format) File "C:\Users\Ben\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\indexing.py", line 960, in getitem return self.obj._get_value(*key, takeable=self._takeable) File "C:\Users\Ben\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\frame.py", line 3622, in _get_value row = self.index.get_loc(index) File "C:\Users\Ben\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pandas\core\indexes\range.py", line 387, in get_loc raise KeyError(key) from err KeyError: 31

Process finished with exit code 1

for category in lev10_Pnlf['Category'].unique():
    x = lev10_Pnlf.loc[lev10_Pnlf['Category'] == category].index.values + 4

    if len(x) >1:
        worksheet1.merge_range(x[0], 0, x[-1], 0, lev10_Pnlf.loc[x[0], 'Category'], merge_format)
    else:
        pass


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source