Use ChatGPT to Improve Code
You can ask ChatGPT for suggestions about how to improve programs that you’ve written. This can be the beginning of a larger strategy that culminates in ChatGPT writing new code. But it’s often best to start with a high-level discussion, just like you would with another engineer. Here’s an example:
Prompt: How could this program to read and analyze survey data in a spreadsheet be improved? Do not write code; just make suggestions.
from
util
import
*
import
pandas
as
pd
df
=
pd
.
read_excel
(
"data.xlsx"
)
df
.
fillna
(
"No answer"
,
inplace
=
True
)
cols
=
df
.
columns
totalrows
=
len
(
df
)
(
"total answers:"
,
totalrows
)
name
=
0
for
col
in
cols
name
+=
1
noans
=
len
(
df
[
df
[
col
]
==
"No answer"
])
nonnull
=
totalrows
-
noans
(
col
)
(
"No answer:"
,
noans
,
"Total answers:"
,
nonnull
)
answers
=
set
(
df
[
col
])
for
answer
in
answers
:
adf
=
df
[
df
[
col
]
==
answer
]
nanswer
=
len
(
adf
)
p
=
pct
(
nanswer
,
nonnull
)
if
answer
!=
"No answer"
:
(
" "
,
answer
,
":"
,
nanswer
,
":"
,
p
)
()
ChatGPT: Here are some suggestions to improve the program:
Function encapsulation: Consider breaking the code into smaller functions, each with a specific task, such as loading data, preprocessing, and analyzing the data. This will improve code readability and make it easier to maintain and debug.
Variable naming: Use more descriptive variable names to make the code more understandable. For instance, instead of using name, you ...
Get Use ChatGPT to Improve Code now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.