Pandas DataFrame | truncate method
Start your free 7-days trial now!
Panda's DataFrame.truncate(~)
method extracts a subset of rows from the DataFrame using truncation.
Parameters
1. before
| int
or string
or date
| optional
Remove all values before this index value. Leaving this out would mean that rows/columns will be included from the beginning.
2. after
| int
or string
or date
| optional
Remove all values after this index value. Leaving this out would mean that rows/columns will be included until the end.
3. axis
| int
or string
| optional
The axis along which to perform the method:
Axis | Description |
---|---|
| Truncate rows |
| Truncate columns |
By default, axis=0
.
4. copy
| bool
| optional
If
True
, then a new DataFrame will be created.If
False
, then a reference to the source DataFrame is returned. This means that modifying the DataFrame returned bytruncate(~)
would also modify the source DataFrame, and vice versa.
By default, copy=True
.
Examples
Truncating rows
Consider the following DataFrame:
df = pd.DataFrame({"A":[1,2,3,4], "B":[5,6,7,8]}, ["a","b","c","d"])df
A Ba 1 5b 2 6c 3 7d 4 8
To truncate rows before index "b"
and after index "c"
:
df.truncate(before="b", after="c") # or axis=0
A Bb 2 6c 3 7
Truncating columns
Consider the following DataFrame:
df = pd.DataFrame({"A":[1,2], "B":[3,4], "C":[5,6], "D":[7,8]})df
A B C D0 1 3 5 71 2 4 6 8
To truncate columns before column "B"
and after column "C"
, set axis=1
:
df.truncate(before="B", after="C", axis=1)
B C0 3 51 4 6