r/learnpython • u/Deep-Ostrich9298 • 1d ago
Pandas scripts I copied together for our weekly reports keep breaking and nobody at work knows Python
I put together a few Python scripts that pull two CSV exports and merge them with pandas.
One of the exports renamed a column and the merge started throwing a KeyError. I still don't really get half of what the script does. Nobody here knows Python.
I want to know these scripts well enough to fix them myself. What helped you go from pasting code to understanding what your own code does?
11
u/atarivcs 1d ago
If you posted the code and the full error, we could explain exactly what the problem is.
And that process might help you understand the code more generally.
3
3
3
u/teetaps 1d ago
Use a notebook to explore the data interactively. Notebooks will allow you to run the code step by step, look at each result as it changes, and experiment with any changes you want to make.
I know Python users hate notebooks, but this is exactly where notebooks become useful
2
2
u/jmacey 1d ago
I really recommend using marimo for this if you do, you can explore pandas dataframes with no extra code as it will display them for you and you can run all sorts of filters ect. https://docs.marimo.io/guides/working_with_data/dataframes/
1
0
u/Designer-Ad-2136 1d ago
Rewrite the script so it has no hard-coded business logic, especially strings, unless they are parameter defaults
-1
u/AdhesivenessFew8441 1d ago
This exact break (an export renames a column, the merge dies with KeyError) is the best place to start learning, because it shows you where the script depends on the data. Three things that helped me with scripts like this: 1) Right after each read_csv, add print(df.columns.tolist()) and print(df.head()). Run it and compare with what the merge expects. Half of understanding pandas code is just seeing what the table looks like at each step. 2) Put every column name the script uses in one place at the top, for example a dict that renames the export columns to your own names (df = df.rename(columns=COLUMN_MAP)). Next time an export changes, you fix one line instead of hunting through the code. 3) Add a check before the merge that lists the missing columns and stops with a clear message, so the error says what changed instead of a KeyError deep in pandas. Then go through the script one line at a time and write a short comment above each line in your own words. If you paste the code and the full error here, people can walk you through it.
17
u/rhacer 1d ago
How did you put together these scripts if you don't know Python?