Python Tutorial: Pandas DataFrame-concat function

Monday, 21 September 2020

Pandas DataFrame-concat function

Add Row/Column to Pandas DataFrame concate() function

Syntax:

result=pd.concate([list of DataFrames],axis=0,ignore_index=False)

 Using ignore_index

The option is used whether or not the original row labels should be retained or not. By default it is false.

Example :

import pandas as pd

SData={"name":['Adil','Deepak','Satyam'],\

       'Accounts':[54,76,87],'English':[89,43,67],\

       'Bst':[56,87,54]}

print("Convert dictionary to dataframe")

df=pd.DataFrame(SData)

print(df)

print()

newDF=pd.DataFrame({'name':['Arif','Dilshad'],'Accounts':[56,79],\

                    'English':[67,87],'Bst':[67,78]},index=[0,1])

print("New Data Frame\n ",newDF)

df2=pd.concat([df,newDF])

print("\nAfter add rows new data frame\n and show index separately\n",df2)

Output :


Using ignore_index=True

 If you want that the resultant object has to follow its own index, then set ignore_index  to True.

Example:

import pandas as pd

SData={"name":['Adil','Deepak','Satyam'],\

       'Accounts':[54,76,87],'English':[89,43,67],\

       'Bst':[56,87,54]}

print("Convert dictionary to dataframe")

df=pd.DataFrame(SData)

print(df)

print()

newDF=pd.DataFrame({'name':['Arif','Dilshad'],'Accounts':[56,79],\

                    'English':[67,87],'Bst':[67,78],'IP':[98,88]},index=[0,1])

print("New Data Frame\n ",newDF)

df2=pd.concat([df,newDF],ignore_index=True)

print("\nafter Ignore Index\n",df2)

 



Add Column to Pandas DataFrame concate() function

You can also specify axis=1 in order or join, merge or concatenate along the columns.

Example : Add column Total_Price is a Dataframe

import pandas as pd

SData={"name":['Adil','Deepak','Satyam'],\

       'Accounts':[54,76,87],'English':[89,43,67],\

       'Bst':[56,87,54]}

print("Convert dictionary to dataframe")

df=pd.DataFrame(SData)

print(df)

Temp=pd.DataFrame({"Total":[]})

df=pd.concat([df,Temp],axis=1)

print(df)

Output: 





No comments:

Post a Comment