如何在 Python Pandas 中索引以特定字符串结尾的点值后四舍五入到零?

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

我有 pandas DataFrame,如下所示:

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

在我的 table 中,“col1”是索引,我只需要索引以“_sum”结尾的这些列中的舍入值。

所以我需要像下面这样的东西:

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

因为只有第一行索引(“col1”)以“_sum”结尾,所以我们将那里的值四舍五入到点后的零位。

如何在 Python Pandas 中做到这一点?

您可以使用布尔索引(但数字现在是 str):

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

打印:

        number
col1          
acb_sum    500
deff     0.509
ghi      0.342

编辑:更改选定的列:

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)

打印:

        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 使用:

         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