MCPcopy Create free account
hub / github.com/dask/dask / boundary_slice

Function boundary_slice

dask/dataframe/methods.py:74–133  ·  view source on GitHub ↗

Index slice start/stop. Can switch include/exclude boundaries. Examples -------- >>> df = pd.DataFrame({'x': [10, 20, 30, 40, 50]}, index=[1, 2, 2, 3, 4]) >>> boundary_slice(df, 2, None) x 2 20 2 30 3 40 4 50 >>> boundary_slice(df, 1, 3) x

(df, start, stop, right_boundary=True, left_boundary=True)

Source from the content-addressed store, hash-verified

72
73
74def boundary_slice(df, start, stop, right_boundary=True, left_boundary=True):
75 """Index slice start/stop. Can switch include/exclude boundaries.
76
77 Examples
78 --------
79 >>> df = pd.DataFrame({'x': [10, 20, 30, 40, 50]}, index=[1, 2, 2, 3, 4])
80 >>> boundary_slice(df, 2, None)
81 x
82 2 20
83 2 30
84 3 40
85 4 50
86 >>> boundary_slice(df, 1, 3)
87 x
88 1 10
89 2 20
90 2 30
91 3 40
92 >>> boundary_slice(df, 1, 3, right_boundary=False)
93 x
94 1 10
95 2 20
96 2 30
97
98 Empty input DataFrames are returned
99
100 >>> df_empty = pd.DataFrame()
101 >>> boundary_slice(df_empty, 1, 3)
102 Empty DataFrame
103 Columns: []
104 Index: []
105 """
106 if len(df.index) == 0:
107 return df
108
109 if not df.index.is_monotonic_increasing:
110 # Pandas treats missing keys differently for label-slicing
111 # on monotonic vs. non-monotonic indexes
112 # If the index is monotonic, `df.loc[start:stop]` is fine.
113 # If it's not, `df.loc[start:stop]` raises when `start` is missing
114 if start is not None:
115 if left_boundary:
116 df = df[df.index >= start]
117 else:
118 df = df[df.index > start]
119 if stop is not None:
120 if right_boundary:
121 df = df[df.index <= stop]
122 else:
123 df = df[df.index < stop]
124 return df
125
126 result = df.loc[start:stop]
127 if not right_boundary and stop is not None:
128 right_index = result.index.get_slice_bound(stop, "left")
129 result = result.iloc[:right_index]
130 if not left_boundary and start is not None:
131 left_index = result.index.get_slice_bound(start, "right")

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected