Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

python - Accounting formatting in Pandas df

Imgur

x=pd.DataFrame([[5.75,7.32],[1000000,-2]])

def money(val):
    """
    Takes a value and returns properly formatted money
    """
    if val < 0:
        return "$({:>,.0f})".format(abs((val)))
    else:
        return "${:>,.0f}".format(abs(val))

x.style.format({0: lambda x: money(x),
                1: lambda x: money(x)
                })

I am trying to get currency to format in the pandas jupyter display with excel accounting formatting. Which would look like the below.

Imgur

I was most successful with the above code, but i also tried a myriad of css and html things, but i am not well versed in the languages so they didn't work really at all.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your output looks like you are using the HTML display in the Jupyter notebook, so you will need to set pre for the white-space style, because HTML collapses multiple whitespace, and use a monospace font, e.g.:

styles = {
    'font-family': 'monospace',
    'white-space': 'pre'
}

x_style = x.style.set_properties(**styles)

Now to format the float, a simple right justified with $ could look like:

x_style.format('${:>10,.0f}')

Float format

This isn't quite right because you want to convert the negative number to (2), and you can do this with nested formats, separating out the number formatting from justification so you can add () if negative, e.g.:

x_style.format(lambda f: '${:>10}'.format(('({:,.0f})' if f < 0 else '{:,.0f}').format(f)))

Accounting Format

Note: this is fragile in the sense it assumes 10 is sufficient width, vs. excel which dynamically left justifies $ to the maximum width of all the values in that column.

An alternative way to do this would be to extend string.StringFormatter to implement the accounting format logic.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...