Page 70 - Informatics_Practices_Fliipbook_Class12
P. 70
3. Concatenate the original DataFrame with the DataFrame constructed in step 2 using Pandas method pd.concat().
groceryDF = pd.read_csv('Grocery.csv')
newPurchase = pd.DataFrame({'Product':['Jeans', 'Chocolate'], 'Category':['Clothes',
'Food'], 'Price':[400, 50], 'Quantity':[2, 4] })
pd.concat([groceryDF, newPurchase])
output:
Product Category Price Quantity
0 Bread Food 20 2
1 Milk Food 60 5
2 Biscuit Food 20 2
3 Bourn-Vita Food 70 1
4 Soap Hygiene 40 4
5 Brush Hygiene 30 2
6 Detergent Household 80 1
7 Tissues Hygiene 30 5
0 Jeans Clothes 400 2
1 Chocolate Food 50 4
Note that the new rows are stored at index 0 and 1. If you want the the newly added rows to be indexed in sequence,
we set the keyword argument ignore_index=True, as shown below:
>>> groceryDF = pd.read_csv('Grocery.csv')
>>> newPurchase = pd.DataFrame({'Product':['Jeans', 'Chocolate'], 'Category':['Clothes',
'Food'], 'Price':[400, 50], 'Quantity':[2, 4] })
>>> pd.concat([groceryDF, newPurchase], ignore_index=True)
output:
Product Category Price Quantity
0 Bread Food 20 2
1 Milk Food 60 5
2 Biscuit Food 20 2
3 Bourn-Vita Food 70 1
4 Soap Hygiene 40 4
5 Brush Hygiene 30 2
6 Detergent Household 80 1
7 Tissues Hygiene 30 5
8 Jeans Clothes 400 2
9 Chocolate Food 50 4
Merging DataFrames
To illustrate merging of the DataFrames. We create two DataFrames of purchases made on two days (to be called day1
and day2) and then concatenate them, as follows:
1. We construct the first DataFrame groceryDF1 by reading the data of purchases on day1 from the csv file
Grocery1.csv.
2. We construct the second DataFrame groceryDF1 by reading the data of purchases on day2 from the csv file
Grocery2.csv.
3. Concatenate the DataFrames groceryDF1 and groceryDF2.
>>> groceryDF1 = pd.read_csv('Grocery1.csv')
>>> print('Day 1 Purchases: ')
>>> print(groceryDF1.head())
>>> groceryDF2 = pd.read_csv('Grocery2.csv')
>>> print('\nDay 2 Purchases: ')
>>> print(groceryDF2.head())
Day 1 Purchases:
Product Category Price Quantity
0 Bread Food 20 2
1 Milk Food 60 5
56 Touchpad Informatics Practices-XII

