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

12

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).

answered question

1 Answer

8

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)

posted this

Have an answer?

JD

Please login first before posting an answer.