Answers for "how to slice by index"

19

python how to slice lists

# Basic syntax:
your_list[start:stop:step]

# Note, Python is 0-indexed
# Note, start is inclusive but stop is exclusive
# Note, if you leave start blank, it defaults to 0. If you leave stop
# 	blank, it defaults to the length of the list. If you leave step
# 	blank, it defaults to 1.
# Note, a negative start/stop refers to the index starting from the end
# 	of the list. Negative step returns list elements from right to left 

# Example usage:
your_list = [0, 1, 2, 3, 4, 5]
your_list[0:5:1]
--> [0, 1, 2, 3, 4] # This illustrates how stop is not inclusive

# Example usage 2:
your_list = [0, 1, 2, 3, 4, 5]
your_list[::2] # Return list items for even indices
--> [0, 2, 4]

# Example usage 3:
your_list = [0, 1, 2, 3, 4, 5]
your_list[1::2] # Return list items for odd indices
--> [1, 3, 5]

# Example usage 4:
your_list = [0, 1, 2, 3, 4, 5]
your_list[4:-6:-1] # Return list items from 4th element from the left to 
#	the 6th element from the right going from right to left
--> [4, 3, 2, 1]
# Note, from the right, lists are 1-indexed, not 0-indexed
Posted by: Guest on October-03-2020
2

pandas df by row index

indices = [133, 22, 19, 203, 14, 1]
df_by_indices = df.iloc[indices, :]
Posted by: Guest on October-22-2020
0

pandas row data to webform

def _getFields(obj, tree=None, retval=None, fileobj=None):
    fieldAttributes = {'/FT': 'Field Type', '/Parent': 'Parent', '/T': 'Field Name', 
    '/TU': 'Alternate Field Name', '/TM': 'Mapping Name', '/Ff': 'Field Flags', 
    '/V': 'Value', '/DV': 'Default Value'}
    if retval is None:
        retval = OrderedDict()
        catalog = obj.trailer["/Root"]
        if "/AcroForm" in catalog:
            tree = catalog["/AcroForm"]
        else:
            return None
    if tree is None:
        return retval

    obj._checkKids(tree, retval, fileobj)
    for attr in fieldAttributes:
        if attr in tree:
            obj._buildField(tree, retval, fileobj, fieldAttributes)
            break

    if "/Fields" in tree:
        fields = tree["/Fields"]
        for f in fields:
            field = f.getObject()
            obj._buildField(field, retval, fileobj, fieldAttributes)

    return retval
Posted by: Guest on October-14-2020
0

add an index column in range dataframe

df = df.loc[df.index.repeat(df['a'])]   
df['c'] = df.groupby(level=0).cumcount() + 1
df = df.reset_index(drop=True)
print (df)
   a  b  c
0  1  x  1
1  2  y  1
2  2  y  2
3  3  z  1
4  3  z  2
5  3  z  3
Posted by: Guest on November-06-2020

Code answers related to "how to slice by index"

Python Answers by Framework

Browse Popular Code Answers by Language