×

How to change the names of Columns in Python

Introduction

To play with huge amounts of data, in Python we require a tool. The tool which is available in Python is Pandas. Pandas is an open-source library. It is used to analyze huge datasets without any difficulty. This is the biggest advantage of Pandas.

By using Pandas, a Data Frame can be created. A Data Frame is a table which contains all the contents of a dataset. This Data Frame helps us to visualize the ugly looking dataset into a good-looking table. So, now let us learn about how to convert the data types of the contents present in the dataset.

Creation of Data Frames

To create a Data Frame, there are few steps. They are

1. Install Pandas (ignore if available)

The command to install Pandas is

pip install pandas

or

python –m pip install pandas

2. Open Python idle window or any Python compiler

3. The first thing we have to do is to import Pandas

We can import Pandas into the program with a command import Pandas as pd

4. Create a dictionary or list or tuple for creating a Data Frame. If we have a dataset we export it into the program with a command like

ds = pd.read_csv(‘File-Name’)

5. Now with a command like

df = pd.DataFrame(dict_name/tuple_name/list_name,columns=’Col_1’,’Col_2’….)

Example:

'''
1.) downloaded pandas library
2.) Opened pandas library
3.) Import pandas library
'''


import pandas as pd


# 4.) A Dataset needs to be created


DataSet={
‘Players’: ['Root','Smith','Kohli','Kane'],
‘Matches’: [24,11,15,6],
‘Runs’: [2595, 779,756,491],
‘AVG’ :[60.25,45.82,29.07,49.10],
‘100s’: [11,1,0,1]
}
#5.) Data Frame Creation
df = pd.DataFrame(DataSet)


print(df)

Output:

Players  Matches  Runs    AVG  100s
0    Root       24          2595  60.25    11
1   Smith       11          779  45.82     1
2   Kohli       15           756  29.07     0
3    Kane        6           491  49.10     1

Now we have created a Data set and also a Data Frame using pandas. Now let us know how to change the names of the rows using some pre-defined methods.

The ways to change the names of columns are:

1. Changing the Name of Column using a Method Columns

This is one of the methods used to change the names columns. This is in-built method used in Data Frames.

Syntax:

DataFrame_name.columns [‘col1_name’, ‘col2_name’,…………………]

Example:

Let us apply this method to the previous data set created.

print(df)


df.columns =['Sportsmen' , 'Matches_Played' , 'Runs_Scored' , 'Average' , 'Centuries' ]
print(df)

Output:

  Players  Matches  Runs    AVG  100s
0    Root       24        2595  60.25    11
1   Smith       11       779    45.82        1
2   Kohli       15         756   29.07       0
3    Kane        6         491   49.10        1
  Sportsmen  Matches_Played  Runs_Scored  Average  Centuries
0      Root              24         2595    60.25         11
1     Smith              11          779    45.82          1
2     Kohli              15          756    29.07          0
3      Kane               6          491    49.10          1

Explanation:

The above output shows the change in the names of the columns.

Here,

Players -> Sportsmen
Matches -> Matches_Played
Runs -> Runs_Scored
AVG -> Average
100s -> Centuries

This is how this method is used to change the names of the columns

2. Rename Method

This is also in-built method present in a Data Frame. This method is also used to change the name columns present in the Data Frame

Syntax:

Data Frame name = Data Frame name .rename( columns = {‘old column name1’ : ‘new column name1}, ‘ old column name 2’ ,’ new columns name 2 } )

Example:

We are again using the same Data Frame created previously.

print(df)


df=df.rename( columns={'AVG': 'Average','100s':'Centuries'})


print(df)

Output:

  Players  Matches  Runs    AVG  100s
0    Root       24  2595  60.25    11
1   Smith       11   779  45.82     1
2   Kohli       15   756  29.07     0
3    Kane        6   491  49.10     1
  Players  Matches  Runs  Average  Centuries
0    Root       24  2595    60.25         11
1   Smith       11   779    45.82          1
2   Kohli       15   756    29.07          0
3    Kane        6   491    49.10          1

This method is more convenient than previous method. This is because in the previous columns method we have to convert all the old column names to new column names.

Whereas in this rename method we can convert only specified column names with mentioning them.

3. Using Indexing Method

Here in this method, we will directly approach the column and change its method with the help assignment operator.

Syntax:

Data Frame Name. column.values[index value] =’ new column name’

Example:

print(df)


df.columns.values[3] = 'Average'
print(df)

Output:

Players  Matches  Runs    AVG  100s
0    Root       24  2595  60.25    11
1   Smith       11   779  45.82     1
2   Kohli       15   756  29.07     0
3    Kane        6   491  49.10     1
  Players  Matches  Runs  Average  100s
0    Root       24  2595    60.25    11
1   Smith       11   779    45.82     1
2   Kohli       15   756    29.07     0
3    Kane        6   491    49.10     1

These are the ways through which we can change the names of columns in python.


Related Topics

How to write a program in python?

How to write a program in python? In python, writing programs is not a big deal. What we need to work on is our logic and some basic rules of this...

4 minutes read.

Programs for Printing Pyramid Patterns in Python

<!-- wp:paragraph --><p>Python supports printing patterns using basic for loops. The number of rows is handled by the first outer loop, while the number of columns is handled by the...

9 minutes read.

Python Loop through a Dictionary

Introduction in this tutorial, we will discuss in python How to Loop Through a Dictionary. In contrast to other Data Types, which can only retain a single value as an element, a Dictionary...

4 minutes read.

Decision Tree in Python

Decision Tree is one of the most essential algorithms in the area of machine learning for classification and regression. But let us first talk about the lifespan of every machine learning...

12 minutes read.

How to make a firewall in Python?

Firewall: The firewall is a network which controls the incoming and outgoing network traffics of a monitor. It blocks the dataset based on the set of rules written in the security...

3 minutes read.

Standard Scaler in SKLearn

The sci kit learns in python is a library thatch is used in machine learning which is used to work on data modeling.It is only focused on the data modeling,...

4 minutes read.

Data Structures and Algorithms using Python | Part 2

Files: A file is a location or information stored in computer storage devices. File handling is essential when the information or the data is to be held permanently. When we try to...

20 minutes read.

Python GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.

Python String lstrip() method

Python String lstrip() method The string. lstrip () method in Python returns a copy of the string with leading characters removed (based on the string argument passed). Syntax string.lstrip([chars]) Parameter chars(optional): This parameter represents a...

1 minute read.

Working with JSON in Python

Python is an Object-Oriented high-level language. Python is designed to be highly beginner-friendly. Python has an English-like syntax, which is very easy to read. In this article, we are going...

4 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

Python Packages

A package is a collection of Python modules that share a similar namespace and are generated by putting all of the modules in a single directory with certain special files...

6 minutes read.

What Does the Percent Sign (%) Mean in Python?

In python, the percent sign is called modulo operator " %, " which returns the rest of partitioning the left-hand operand by the right-hand operand. Example: value1 = 8 value2 = 2 remainder =...

4 minutes read.

Python AIOHTTP

Python 3.5 introduced some new syntax that makes it simpler for developers to make asynchronous programmes and packages. Aiohttp, an HTTP client/server for asyncio, is one such package. In essence,...

3 minutes read.

Selection Sort Using Python

Selection sort is a type of sorting algorithm which is based on sorting elements in increasing order or ascending order through comparison. This sorting technique does not take extra space...

3 minutes read.

Is Python Object Oriented Programming language

In this tutorial, we will see whether python also belongs to an object-oriented programming language like several others. We will also see the advantages of using OOPs. Further, we will...

4 minutes read.

Artificial intelligence mini projects ideas in python

Artificial intelligence "The human race started from the invention of the wheel", and today we are about to advance to the Industrial level 4.0, where machines can work, talk, think and...

6 minutes read.

Python int()

Python int() class The int() class in Python returns an integer object constructed from a number or string x. Syntax class int(x, base=10) Parameter x: This parameter represents a number or a string that can be converted into...

1 minute read.

Import Function in Python

In Python programming language, the import keyword plays an important role in the whole code because it makes one module make available in another module. Import is used to structure...

3 minutes read.

Nested for Loop in Python

"Loop" is one of the foundation concepts to learn programming in any language. Nested loops are significant steps in solving many types of problems, ranging from basic to complex scenarios....

9 minutes read.