In Pandas, there is a new styler option for formatting CSS ( http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.core.style.Styler.html ).
Before, when I wanted to make my numbers into accounting/dollar terms, I would use something like below:
df = pd.DataFrame.from_dict({'10/01/2015': {'Issued': 200}}, orient='index')
html = df.to_html(formatters={'Issued': format_money})
format_money function:
def format_money(item):
return '${:,.0f}'.format(item)
Now I want to use the Style options, and keep my $ formatting. I'm not seeing any way to do this.
Style formatting for example would be something like this:
s = df.style.bar(color='#009900')
#df = df.applymap(config.format_money) -- Doesn't work
html = s.render()
This would add bars to my HTML table like so(Docs here: http://pandas.pydata.org/pandas-docs/stable/style.html):
So basically, how do I do something like add the bars, and keep or also add in the dollar formatting to the table? If I try to do it before, the Style bars don't work because now they can't tell that the data is numerical and it errors out. If I try to do it after, it cancels out the styling.
That hasn't been implemented yet (version 0.17.1) - but there is a pull request for that (https://github.com/pydata/pandas/pull/11667) and should come out in 0.18. For now you have to stick to using the formatters.
Related
I'm trying to keep only the text after "Background", but I didn't have success trying to do it. For instance, I have a comment like this:
05/2022: AB: 6/20/22 - I'm learning how to use pandas library.
Background: I'm trying to learn python.
How can I make all cells have only the background comment? It should look like this:
Background: I'm trying to learn python.
Please see my code below:
import pandas as pd
df = pd.read_excel(r"C:\Users\R\Desktop\PythonLib\data\52022.xlsx")
comments = df["Comment"]
df['new_background'] = df["Comment"].str.split('Background:').str[0]
print(df["new_background"])
You should provide a sample of your data.
That said, you should probably do:
df['new_background'] = df["Comment"].str.replace(r'.*(?=Background:)',
'', regex=True)
Or, if you want NaN in case of missing background:
df['new_background'] = df["Comment"].str.extract(r'(Background:.*)')
The tooltip example presented in the reference guide show the following examples of formatting:
hover.tooltips = [
("index", "$index"),
("(x,y)", "($x, $y)"),
("radius", "#radius"),
("fill color", "$color[hex, swatch]:fill_color"),
("foo", "#foo"),
("bar", "#bar"),
("baz", "#baz{safe}"),
("total", "#total{$0,0.00}"
The 3 examples {safe}, {$0,0.00} and "$color[hex, swatch]:fill_color" are not clear: where can i find some documentation on them?
Basically I would like to understand what is possible and what isn't.
At the moment (for instance) I have 1 input that us a very long string (its a newspaper article) that I would like to format so it only shows the x first characters.
Other example I have a field #datetime that is retrieving its value from a datetime index. At the moment the tooltip displays that value as a int64 character. How to use a format tool such as Timestamp.strftime("%d-%m-%Y") so that it shows the date time in human readable format?
But I would like to have a clearer overview of what is possible/how that aspect of bokeh works
Since this answer was originally posted, new work has gone into Bokeh to make things simpler. A datetime field can be formatted as a datetime directly by the hover tool, by specifying a formatter, e.g.:
HoverTool(tooltips=[('label', '#datetime{%F}')],
formatters={'datetime': 'datetime'})
It is no longer necessary to pre-format date fields in the data source as below (although it certainly still works). For more information see Formatting Tooltip Fields
OLD ANSWER:
This is still an open issue for the project:
https://github.com/bokeh/bokeh/issues/1239
However, given some other recent work, this should now be fairly easy to implement this feature in a natural way. I have scheduled the task for the next 0.12.6 milestone.
Also, although Bokeh has extensive and rich documentation, there are still occasional gaps. This happens to be one of them, unfortunately. I note that there is an open issue to improve this:
https://github.com/bokeh/bokeh/issues/2595
I've updated it to make sure it is also included in the 0.12.6 milestone.
In the mean time, your best option is to pre-format the data as you want it to appear in the tooltip in Python. Then add a column to your data source that has the formatted version, the configure the hover tool to display this column:
source.data['formatted_date'] = my_pretty_print(source.date['date'])
hover.tooltips = [ ("date", "#formatted_date") ]
I want to write a report for classes in Jupyter notebook. I'd like to count some stuff, generate some results and include them in markdown. Can I set the output of the cell to be interpreted as markdown?
I'd like such command: print '$\phi$' to generate phi symbol, just like in markdown.
In other words, I'd like to have a template made in markdown and insert the values generated by the program written in the notebook. Recalculating the notebook should generate new results and new markdown with those new values inserted. Is that possible with this software, or do I need to replace the values by myself?
The functions you want are in the IPython.display module.
from IPython.display import display, Markdown, Latex
display(Markdown('*some markdown* $\phi$'))
# If you particularly want to display maths, this is more direct:
display(Latex('\phi'))
You are basically asking for two different things:
Markdown cells outputting code results.
I'd like to count some stuff, generate some results and include them in markdown. [...] I'd like to have a template in markdown and insert values generated by the program in the notebook
Code cells outputting markdown
I'd like such command: print '$\phi$' to generate phi symbol, just like in markdown.
Since 2. is already covered by another answer (basically: use Latex() or Markdown() imported from IPython.display), I will focus on the first one:
1. Markdown Template with inserted variables
With the Jupyter extension Python Markdown it actually is possible to do exactly what you describe.
Installation instructions can be found on the github page of nbextensions. Make sure you'll enable the python markdown extension using a jupyter command or the extension configurator.
With the extension, variables are accessed via {{var-name}}. An example for such a markdown template could look like this:
Python Code in Markdown Cells
The variable a is {{a}}
You can also embed LateX: {{b}} in here!
Even images can be embedded: {{i}}
Naturally all variables or images a, b, i should be set in previous code. And of course you may also make use of Markdown-Latex-style expressions (like $\phi$) without the print command. This image is from the wiki of the extension, demonstrating the capability.
Further info on this functionality being integrated into ipython/jupyter is discussed in the issue trackers for ipython and jupyter.
As an addition to Thomas's answer. Another easier way to render markdown markup is to use display_markdown function from IPython.display module:
from IPython.display import display_markdown
display_markdown('''## heading
- ordered
- list
The table below:
| id |value|
|:---|----:|
| a | 1 |
| b | 2 |
''', raw=True)
Output below:
Usage example could be found on Google Colab Notebook
Another option is to use Rich for Markdown rendering and UnicodeIt for symbols. It has some limitations, as Rich uses CommonMark, which does not support tables, for example. Rich has other ways to render tables though; this is detailed in the documentation.
Here is an example:
from rich.markdown import Markdown
import unicodeit
alpha = unicodeit.replace('\\alpha')
epsilon = unicodeit.replace('\\epsilon')
phi = unicodeit.replace('\\phi')
MARKDOWN = f"""
# This is an h1
Rich can do a pretty *decent* job of rendering markdown.
1. This is a list item
2. This is another list item
## This is an h2
List of **symbols**:
- alpha: {alpha}
- epsilon: {epsilon}
- phi: {phi}
This is a `code` snippet:
```py
# Hello world
print('Hello world')
```
This is a blockquote:
> Rich uses [CommonMark](https://commonmark.org/) to parse Markdown.
---
### This is an h3
See [Rich](https://github.com/Textualize/rich) and [UnicodeIt](https://github.com/svenkreiss/unicodeit) for more information.
"""
Markdown(MARKDOWN)
... which produces the following output:
from tabulate import tabulate
from IPython.display import Markdown
A2 = {
'Variable':['Bundle Diameter','Shell Diameter','Shell Side Cross Flow area','Volumetric Flowrate','Shell Side Velocity'],
'Result':[3.4, 34, 78.23, 1.0 , 2.0],
'Unit' : ['$in$', '$in$', '$ft^2$', '$ft^{3}s^{-1}$', '$fts^{-1}$']}
temp_html=tabulate(A2, headers='keys', tablefmt='html')
Markdown(temp_html.replace('<table>','<table style="width:50%">'))
.replace() usage will not break latex code & avoid column(s) overstrech. This way one can dynamically generate tables with Latex
I was wondering whether it is possible to process a string in python, using sphinx. Basically, I would like to pass a string containing restructured text to sphinx, and then generate the corresponding HTML output. I meant something like this
import sphinx.something
s = 'some restructured text'
html_out = sphinx.something(s)
However, I could not find anything along these lines. So, is this possible, and if so, how would one do this?
The quickest solution I've seen is:
from docutils.examples import html_body
def rst(rstStr):
return html_body(rstStr, input_encoding='utf-8',
output_encoding='utf-8').strip()
I'd be interested myself in better solutions..
I'm trying to build a blog system. So I need to do things like transforming '\n' into < br /> and transform http://example.com into < a href='http://example.com'>http://example.com< /a>
The former thing is easy - just using string replace() method
The latter thing is more difficult, but I found solution here: Find Hyperlinks in Text using Python (twitter related)
But now I need to implement "Edit Article" function, so I have to do the reverse action on this.
So, how can I transform < a href='http://example.com'>http://example.com< /a> into http://example.com?
Thanks! And I'm sorry for my poor English.
Sounds like the wrong approach. Making round-trips work correctly is always challenging. Instead, store the source text only, and only format it as HTML when you need to display it. That way, alternate output formats / views (RSS, summaries, etc) are easier to create, too.
Separately, we wonder whether this particular wheel needs to be reinvented again ...
Since you are using the answer from that other question your links will always be in the same format. So it should be pretty easy using regex. I don't know python, but going by the answer from the last question:
import re
myString = 'This is my tweet check it out http://tinyurl.com/blah'
r = re.compile(r'(http://[^ ]+)')
print r.sub(r'\1', myString)
Should work.