How to print a variable with underscore in its name?
The print command will be printed and as always in LaTeX the underscore will give errors.
You can suppress the direct printing by setting the autoprint variable to false, and then use \stdoutpythontex
or \printpythontex
to print after the code block.
In a current latex the filecontents package is no longer needed.
\documentclass{article}
\begin{filecontents*}[overwrite]{provapd.txt}
user_id|age
1|20
2|25
3|30
4|35
\end{filecontents*}
\usepackage{pythontex}
\begin{document}
prova pandas
\setpythontexautoprint{false}
\begin{pycode}
import pandas as pd
users = pd.read_table(r'provapd.txt',
sep='|', index_col='user_id')
print(users.age.mean())
print(users.head(3))
\end{pycode}
STDOUT
\stdoutpythontex[verbatim]
PRINT
\printpythontex[verbatim]
\end{document}
I got this:
% arara: pdflatex: { shell : yes }
% arara: pythontex
% arara: pdflatex: { shell : yes }
\documentclass{article}
\usepackage{filecontents}
\begin{filecontents*}{provapd.txt}
user_id|age
1|20
2|25
3|30
4|35
\end{filecontents*}
\usepackage{pythontex}
\begin{document}
prova pandas
\begin{pycode}
import pandas as pd
users = pd.read_table(r'provapd.txt',
sep='|', index_col='user_id')
print(users.age.mean())
print('\n\n')
s=str(users.head(3))
s = s.replace('_','\_').replace('\n','\n\n')
print(s)
\end{pycode}
\end{document}
Sadly, I dont know how to put the output here. I added double newlines in there to separate the mean value and data frame content, converted the output to its string representation and worked with it as a simple string, replacing anything neccessary. Sadly, that led to separating ID and age with newlines (which is weird).
Anyhow, this approach can be used anytime and you can make the output of pandas dataframe into LaTeX table by performing string replacement into form of LaTeX tabular environment...
EDIT: Now it works just about fine:
% arara: pdflatex: { shell : yes }
% arara: pythontex
% arara: pdflatex: { shell : yes }
\documentclass{article}
\usepackage{filecontents}
\begin{filecontents*}{provapd.txt}
user_id|age
1|20
2|25
3|30
4|35
\end{filecontents*}
\usepackage{pythontex}
\begin{document}
prova pandas
\begin{pycode}
import pandas as pd
users = pd.read_table(r'provapd.txt',
sep='|', index_col='user_id')
print(users.age.mean())
print('\n\n')
s=str(users.head(3))
s = s.replace('_','\_').replace('\n',' ',1).replace('\n','\n\n')
print(s)
\end{pycode}
\end{document}
Note the first replacement - string.replace function takes optional, thirst argument, which is "count" - how many replacements should be performed. In that case, exactly one (first) is what you need.