Answers for "set_index python"

3

how to set index pandas

# assignment copy
df = df.set_index('month')

# or inplace
df.set_index('month', inplace=True)

#      year   sale  month            month  year   sale
#  0   2012   55    1                1      2012   55
#  1   2014   40    4       =>       4      2014   40
#  2   2013   84    7                7      2013   84
#  3   2014   31    10               10     2014   31
Posted by: Guest on March-15-2021
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
5

how to change index in dataframe python

index = [1,2]
df.index = index
Posted by: Guest on April-23-2020

Python Answers by Framework

Browse Popular Code Answers by Language