Floor or ceiling of a pandas series in python?

前端 未结 4 1972
轻奢々
轻奢々 2020-12-03 00:39

I have a pandas series series. If I want to get the element-wise floor or ceiling, is there a built in method or do I have to write the function and use apply?

相关标签:
4条回答
  • 2020-12-03 00:55

    clip_lower / clip_upper

    With Pandas, you can set a floor via clip_lower or ceiling via clip_upper:

    s = pd.Series([-1, 0, -5, 3])
    
    print(s.clip_lower(0))
    # 0    0
    # 1    0
    # 2    0
    # 3    3
    # dtype: int64
    
    print(s.clip_upper(0))
    # 0   -1
    # 1    0
    # 2   -5
    # 3    0
    # dtype: int64
    

    clip

    pd.Series.clip supports more generalised functionality, e.g. applying and flooring a ceiling simultaneously, e.g. s.clip(-1, 1).

    0 讨论(0)
  • 2020-12-03 01:03

    UPDATE: THIS ANSWER IS WRONG, DO NOT DO THIS

    Explanation: using Series.apply() with a native vectorized Numpy function makes no sense in most cases as it will run the Numpy function in a Python loop, leading to much worse performance. You'd be much better off using np.floor(series) directly, as suggested by several other answers.

    You could do something like this using NumPy's floor, for instance, with a dataframe:

    floored_data = data.apply(np.floor)
    

    Can't test it right now but an actual and working solution might not be far from it.

    0 讨论(0)
  • 2020-12-03 01:07

    You can use NumPy's built in methods to do this: np.ceil(series) or np.floor(series).

    Both return a Series object (not an array) so the index information is preserved.

    0 讨论(0)
  • I am the OP, but I tried this and it worked:

    np.floor(series)
    
    0 讨论(0)
提交回复
热议问题