0 votes
in Python Pandas by
How to add an Index, row, or column to a Pandas DataFrame?

1 Answer

0 votes
by
Adding an Index to a DataFrame

Pandas allow adding the inputs to the index argument if you create a DataFrame. It will make sure that you have the desired index. If you don?t specify inputs, the DataFrame contains, by default, a numerically valued index that starts with 0 and ends on the last row of the DataFrame.

Adding Rows to a DataFrame

We can use .loc, iloc, and ix to insert the rows in the DataFrame.

The loc basically works for the labels of our index. It can be understood as if we insert in loc[4], which means we are looking for that values of DataFrame that have an index labeled 4.

The iloc basically works for the positions in the index. It can be understood as if we insert in iloc[4], which means we are looking for the values of DataFrame that are present at index ‘4`.

The ix is a complex case because if the index is integer-based, we pass a label to ix. The ix[4] means that we are looking in the DataFrame for those values that have an index labeled 4. However, if the index is not only integer-based, ix will deal with the positions as iloc.

Adding Columns to a DataFrame

If we want to add the column to the DataFrame, we can easily follow the same procedure as adding an index to the DataFrame by using loc or iloc.

Add row with specific index name:

import pandas as pd

employees = pd.DataFrame(

    data={'Name': ['John Doe', 'William Spark'],

          'Occupation': ['Chemist', 'Statistician'],

          'Date Of Join': ['2018-01-25', '2018-01-26'],

          'Age': [23, 24]},

    index=['Emp001', 'Emp002'],

    columns=['Name', 'Occupation', 'Date Of Join', 'Age'])

print("\n------------ BEFORE ----------------\n")

print(employees)

employees.loc['Emp003'] = ['Sunny', 'Programmer', '2018-01-25', 45]

print("\n------------ AFTER ----------------\n")

print(employees)

OUTPUT :

C:\pandas>python example22.py

 

------------ BEFORE ----------------

 

                 Name    Occupation Date Of Join  Age

Emp001       John Doe       Chemist   2018-01-25   23

Emp002  William Spark  Statistician   2018-01-26   24

 

------------ AFTER ----------------

 

                 Name    Occupation Date Of Join  Age

Emp001       John Doe       Chemist   2018-01-25   23

Emp002  William Spark  Statistician   2018-01-26   24

Emp003          Sunny    Programmer   2018-01-25   45

Related questions

0 votes
asked Aug 13, 2021 in Python Pandas by SakshiSharma
0 votes
asked Aug 14, 2021 in Python Pandas by SakshiSharma
...