Using Pandas concat method, we can concatenate the cotent of one ore more data frames.
Example
data1 = { 'Name': ['Krishna', 'Chamu', 'Joel'],
'Age': [34, 25, 29],
'City': ['Bangalore', 'Chennai', 'Hyderabad'],
'Gender': ['Male', 'Female', 'Male'],
'Weight': [74, 58, 85]}
data2 = { 'Name': ['Gopi', 'Sravya', "Raj"],
'Age': [41, 52, 23],
'City': ['Hyderabad', 'Bangalore', 'Chennai'],
'Gender': ['Male', 'Female', 'Male'],
'Weight': [87, 63, 79]}
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
final_df = pd.concat([df1, df2])
In the above example, I defined two dataframe df1, df2 and used concat method to concatenate the content of dtaaframes df1 and df2. 'final_df' point to below content.
Name Age City Gender Weight 0 Krishna 34 Bangalore Male 74 1 Chamu 25 Chennai Female 58 2 Joel 29 Hyderabad Male 85 0 Gopi 41 Hyderabad Male 87 1 Sravya 52 Bangalore Female 63 2 Raj 23 Chennai Male 79
As you see the above output, index numbers are preserved from original dataframes. We can ignore the indexes from original dataframes by passing the argument ignore_index to True.
Find the below working application.
concat_dfs.py
import pandas as pd
data1 = { 'Name': ['Krishna', 'Chamu', 'Joel'],
'Age': [34, 25, 29],
'City': ['Bangalore', 'Chennai', 'Hyderabad'],
'Gender': ['Male', 'Female', 'Male'],
'Weight': [74, 58, 85]}
data2 = { 'Name': ['Gopi', 'Sravya', "Raj"],
'Age': [41, 52, 23],
'City': ['Hyderabad', 'Bangalore', 'Chennai'],
'Gender': ['Male', 'Female', 'Male'],
'Weight': [87, 63, 79]}
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
print('df1')
print(df1)
print('\ndf2')
print(df2)
final_df = pd.concat([df1, df2])
print('\nDataframe after concatenating df1 and df2 data')
print(final_df)
final_df = pd.concat([df1, df2], ignore_index=True)
print('\nDataframe after concatenating df1 and df2 data by ignoring index')
print(final_df)
Output
df1 Name Age City Gender Weight 0 Krishna 34 Bangalore Male 74 1 Chamu 25 Chennai Female 58 2 Joel 29 Hyderabad Male 85 df2 Name Age City Gender Weight 0 Gopi 41 Hyderabad Male 87 1 Sravya 52 Bangalore Female 63 2 Raj 23 Chennai Male 79 Dataframe after concatenating df1 and df2 data Name Age City Gender Weight 0 Krishna 34 Bangalore Male 74 1 Chamu 25 Chennai Female 58 2 Joel 29 Hyderabad Male 85 0 Gopi 41 Hyderabad Male 87 1 Sravya 52 Bangalore Female 63 2 Raj 23 Chennai Male 79 Dataframe after concatenating df1 and df2 data by ignoring index Name Age City Gender Weight 0 Krishna 34 Bangalore Male 74 1 Chamu 25 Chennai Female 58 2 Joel 29 Hyderabad Male 85 3 Gopi 41 Hyderabad Male 87 4 Sravya 52 Bangalore Female 63 5 Raj 23 Chennai Male 79
Previous Next Home
No comments:
Post a Comment