Tuesday 6 February 2024

Pandas: Apply string methods on row index labels

In a pandas DataFrame, the index property represents the row labels or index labels of the DataFrame.

 

df.index = df.index.str.upper()

 

Above snippet convert all the row labels to uppercase.

 

string_methods_on_row_labels.py

import pandas as pd

# Create a sample DataFrame
data = {'Name': ['Krishna', 'Sailu', 'Joel', 'kranthi', 'Jitendra', 'Kumar'],
        'Hobbies': ['Football,Cricket', 'Tennis, cricket', 'Trekking, reading books', 'Chess', 'Read Books', 'Cricket']}
df = pd.DataFrame(data)

# Set the Name column as row label
df.set_index('Name', inplace=True)

print('Original DataFrame')
print(df)

df.index = df.index.str.upper()
print('\nConverted row index labels to upper case :\n', df)

 

Output

Original DataFrame
                          Hobbies
Name                             
Krishna          Football,Cricket
Sailu             Tennis, cricket
Joel      Trekking, reading books
kranthi                     Chess
Jitendra               Read Books
Kumar                     Cricket

Converted row index labels to upper case :
                           Hobbies
Name                             
KRISHNA          Football,Cricket
SAILU             Tennis, cricket
JOEL      Trekking, reading books
KRANTHI                     Chess
JITENDRA               Read Books
KUMAR                     Cricket

 

 

  

Previous                                                 Next                                                 Home

No comments:

Post a Comment