How to round to zeroes place after dot only values where index end with specific string in Python Pandas?

Viewed 33

I have pandas DataFrame like below:

col1    | number
--------------------
acb_sum | 500.000
deff     | 0.509
ghi     | 0.342

In my table "col1" is index and I need round values only in these columns where index ends with "_sum".

So as a result I need to have something like below:

col1    | number
--------------------
acb_sum | 500
deff     | 0.509
ghi     | 0.342

Because only in the first row index ("col1") ends with "_sum" so we round value there to zeroes places after dot.

How can I do that in Python Pandas ?

1 Answers

You can use boolean indexing (but the number is now str):

mask = df.index.str.endswith("_sum")
df.loc[mask, "number"] = df.loc[mask, "number"].apply(lambda x: str(round(x)))
print(df)

Prints:

        number
col1          
acb_sum    500
deff     0.509
ghi      0.342

EDIT: To change selected columns:

cols_to_change = ["number1", "number2", "number3"]
mask = df.index.str.endswith("_sum")
df.loc[mask, cols_to_change] = df.loc[mask, cols_to_change].apply(
    lambda x: [str(round(v)) for v in x]
)
print(df)

Prints:

        number1 number2    xxx number3
col1                                  
acb_sum     500     400  111.3     200
deff      0.509   401.0  112.3   201.0
ghi       0.342   402.0  113.3   202.0

df used:

         number1  number2    xxx  number3
col1                                     
acb_sum  500.000    400.0  111.3    200.0
deff       0.509    401.0  112.3    201.0
ghi        0.342    402.0  113.3    202.0
Related