Removing animation keyframes outside of a specified range
I got it working thanks to batFINGER's comment.
My final code looked like this:
import numpy as np
def action_slice(action, start_frame, end_frame, shift=True): 
    copy = bpy.data.actions.new(action.name)
    copy.id_root = action.id_root
    
    for fcurve in action.fcurves:
        kfs = np.empty(len(fcurve.keyframe_points) &lt;&lt; 1)
        fcurve.keyframe_points.foreach_get(&quot;co&quot;, kfs)
        kfs = kfs.reshape((-1, 2))
        _fc = copy.fcurves.new(
                fcurve.data_path,
                index = fcurve.array_index
                )
        _fc.keyframe_points.add(0)
        _kfs = kfs[
                np.logical_and(
                    kfs[:,0] &gt;= start_frame, 
                    kfs[:,0] &lt;= end_frame
                    )
                ]
        if shift:
            _kfs[:,0] -= start_frame
        _fc.keyframe_points.add(_kfs.shape[0])
        _fc.keyframe_points.foreach_set(&quot;co&quot;, _kfs.ravel())
    return copy

def object_do_slice(string, endframe):
    ob = bpy.data.objects.get(string)#context.object
    ad = ob.animation_data
    action = ad.action if ad else None
    if action:
        ad.action = action_slice(action, 1, endframe, shift=True)

object_do_slice(&quot;Root&quot;,framelength+1)