Answers for "set index python"

2

set index in datarame

df = df.set_index('col')
Posted by: Guest on May-18-2020
1

add an index column pandas

import numpy as np
import pandas as pd
df = pd.DataFrame({'month': [2, 5, 8, 10],
                   'year': [2017, 2019, 2018, 2019],
                   'sale': [60, 45, 90, 36]})
df.set_index('month')
Posted by: Guest on July-01-2020
1

how to index a set in python

"""
You can't index a set in python.
The concept of sets in Python is inspired in Mathmatics. If you are interested
in knowing if any given item belongs in a set, it shouldn't matter "where" in
the set that item is located. With that being said, if you still want to
accomplish this, this code should work, and, simultaneously, show why it's a 
bad idea
"""

def get_set_element_from_index (input_set : set, target_index : int):
    if target_index < 0:
        target_index = len(input_set) + target_index
    index = 0
    for element in input_set:
        if index == target_index:
            return element
        index += 1
    raise IndexError ('set index out of range')

my_set = {'one','two','three','four','five','six'}
print (my_set) # unpredictable output. Changes everytime you run the script
# let's say the previous print nails the order of the set (same as declared)
print(get_set_element_from_index(my_set, 0))  # prints 'one'
print(get_set_element_from_index(my_set, 3))  # prints 'four'
print(get_set_element_from_index(my_set, -1)) # prints 'six'
print(get_set_element_from_index(my_set, 6))  # raises IndexError
Posted by: Guest on June-02-2021

Python Answers by Framework

Browse Popular Code Answers by Language