PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

[FIXED] How can I round each entry (which is a tuple) of a pandas dataframe in Python?

 August 10, 2022     decimal, pandas, python, rounding     No comments   

Issue

import pandas as pd

D = {"a":[(1.0411070751196425, 1.048179051450828),(0.8020630165032718, 0.8884133074952416)], 
     "b":[(1.0411070751196425, 1.048179051450828),(0.8020630165032718, 0.8884133074952416)],
     "c":[(1.0411070751196425, 1.048179051450828),(0.8020630165032718, 0.8884133074952416)], 
     "d":[(1.0411070751196425, 1.048179051450828),(0.8020630165032718, 0.8884133074952416)]}

D = pd.DataFrame(D)

Suppose I have such a pandas dataframe whose entries are tuples. When I print out this dataframe, how can I only display each number to 4 decimals? For example, the complete entry is (1.0411070751196425, 1.048179051450828), and I wanna display (1.0411, 1.0482).


Solution

Use DataFrame.applymap for elementwise processing with generator comprehension and tuples:

D = D.applymap(lambda x: tuple(round(y,4) for y in x))
print (D)
                  a                 b                 c                 d
0  (1.0411, 1.0482)  (1.0411, 1.0482)  (1.0411, 1.0482)  (1.0411, 1.0482)
1  (0.8021, 0.8884)  (0.8021, 0.8884)  (0.8021, 0.8884)  (0.8021, 0.8884)


Answered By - jezrael
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,215,236

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing