Paw in Data
Paw in Data

Reputation: 1554

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

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

Upvotes: 1

Views: 343

Answers (1)

jezrael
jezrael

Reputation: 862731

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)

Upvotes: 4

Related Questions