There are situations where we have to append the intermediate results of a loop operation and create a single data frame.In this blog, we will look at how we can do this using pandas¶
In [1]:
import pandas as pd
import numpy as np
Step 1: Creating dummy data for row wise binding¶
In [17]:
row_df1=pd.DataFrame([np.array(["Product_Category","Product_Category","Product_Category"]),
np.array(["PC","Print","Services"]),
np.array([50,30,20])]).T
row_df1.columns=['Feature','Levels','Perc_Share']
row_df1
Out[17]:
Feature | Levels | Perc_Share | |
---|---|---|---|
0 | Product_Category | PC | 50 |
1 | Product_Category | 30 | |
2 | Product_Category | Services | 20 |
In [18]:
row_df2=pd.DataFrame([np.array(["Region","Region","Region","Region"]),
np.array(["East","West","North","South"]),
np.array([50,25,15,10])]).T
row_df2.columns=['Feature','Levels','Perc_Share']
row_df2
Out[18]:
Feature | Levels | Perc_Share | |
---|---|---|---|
0 | Region | East | 50 |
1 | Region | West | 25 |
2 | Region | North | 15 |
3 | Region | South | 10 |
row_df1 and row_df2 are result of an operation where we are trying to understand percentage share of sales for Product Category and by Region.In order to consolidate results, we need to combined row_df1 and row_df2 into a single data frame¶
Step 2: Appending row_df1 and row_df2¶
In [19]:
row_wise_append=pd.concat([row_df1,row_df2],axis=0)
row_wise_append
Out[19]:
Feature | Levels | Perc_Share | |
---|---|---|---|
0 | Product_Category | PC | 50 |
1 | Product_Category | 30 | |
2 | Product_Category | Services | 20 |
0 | Region | East | 50 |
1 | Region | West | 25 |
2 | Region | North | 15 |
3 | Region | South | 10 |
Step 3: Creating dummy data for column wise binding¶
In [37]:
col_df1=pd.DataFrame([np.array(["Week1","Week1","Week1"]),
np.array(["PC","Laptop","Services"]),
np.random.normal(30,2,3)]).T
col_df1.columns=['Week','Product_Category','Sales_W1']
col_df1
Out[37]:
Week | Product_Category | Sales_W1 | |
---|---|---|---|
0 | Week1 | PC | 25.436445 |
1 | Week1 | Laptop | 29.492091 |
2 | Week1 | Services | 28.286619 |
In [38]:
col_df2=pd.DataFrame([np.array(["Week2","Week2","Week2"]),
np.array(["PC","Laptop","Services"]),
np.random.normal(30,2,3)]).T
col_df2.columns=['Week','Product_Category','Sales_W2']
col_df2
Out[38]:
Week | Product_Category | Sales_W2 | |
---|---|---|---|
0 | Week2 | PC | 29.962953 |
1 | Week2 | Laptop | 27.875145 |
2 | Week2 | Services | 33.107039 |
col_df1 and col_df2 are result of an operation where we are trying to understand Weekly sales for Product Category.In order to consolidate results, we need to combined col_df1 and col_df2 into a single data frame¶
In [42]:
col_wise_append = pd.concat([col_df1,col_df2['Sales_W2']],axis=1)
col_wise_append
Out[42]:
Week | Product_Category | Sales_W1 | Sales_W2 | |
---|---|---|---|---|
0 | Week1 | PC | 25.436445 | 29.962953 |
1 | Week1 | Laptop | 29.492091 | 27.875145 |
2 | Week1 | Services | 28.286619 | 33.107039 |
No comments:
Post a Comment