看过来
《pandas 教程》 持续更新中,提供建议、纠错、催更等加作者微信: gr99123(备注:pandas教程)和关注公众号「盖若」ID: gairuo。跟作者学习,请进入 Python学习课程。欢迎关注作者出版的书籍:《深入浅出Pandas》 和 《Python之光》。
(编码题)把负数直接清零。8 月 5 天的利润(万元):
import pandas as pd
profit = pd.Series([10, -5, 20, -3, 15],
index=pd.date_range("2024-08-01", periods=5),
name="利润")
用 一行 mask()
把 负数 设为 0,其余保留原值,并打印结果。
代码如下:
clean = profit.mask(profit < 0, 0)
print(clean)
输出:
2024-08-01 10
2024-08-02 0
2024-08-03 20
2024-08-04 0
2024-08-05 15
dtype: int64
(完)
更新时间:2025-08-31 12:11:32 标签:pandas python 负数 清零