Page 74 - Informatics_Practices_Fliipbook_Class12
P. 74
1 Milk Food 60 5
2 Biscuit Food 20 2
3 Bourn-Vita Food 70 1
4 Soap Hygiene 40 4
Suppose, we wish to transform all column names by converting them to upper case. Python dataframe
provides method map() which takes the name of the function to be applied on all column names.
For example, the following code snippet converts all column names to uppercase using the map()
function as shown below:
>>> groceryDF.columns = groceryDF.columns.map(str.upper)
>>> print(groceryDF.head())
ITEM NAME 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
Similarly, we may rename indexes to make them more readable or to facilitate analysis being carried
out. For example, we wish to rename indexes as P1, P2, ... P20 to denote Product 1, Product 2,... Product
20 being purchased. We may do so using the method rename() and keyword argument index as shown
below:
>>> groceryDF.rename(index= {i: 'P'+str(i+1) for i in range(0, 20)},
inplace=True)
>>> print(groceryDF.head())
In this example, we use the rename() method and pass a dictionary to the index parameter. The keys
of the dictionary represent the current index labels (0, 1, 2..), and the values represent the new labels.
Setting inplace=True modifies the DataFrame in place.
Pandas method pd.concat() allow us to concatenate a DataFrame with the another DataFrame.
Pandas method drop() can be used to drop a column or row from the DataFrame.
The rename() method in Pandas is used to rename columns. It allows us to specify new names for one or more
columns using a dictionary. The syntax for using the rename() method to rename columns is as follows:
df.rename(columns={'current_name': 'new_name'}, inplace=True)
We may also rename columns in a Pandas DataFrame is by specifying the complete list of names of the columns,
retaining some of the column names as it is while modifying some others by assigning, and assigning it to attribute
columns of groceryDF.
1. Consider the DataFrame employeeDF and rename the column Name to EmpName.
2. Add a column IncrementedSalary with salary of all employees incremented by 50000.
2.9 Writing to csv file
Suppose, after updating the DataFrame by adding a column of Total Price, we wish to saved the updated
DataFrame to file GroceryV2.csv. We can save the DataFrame object as CSV (Comma-Separated Values) file using
the to_csv() function of Pandas DataFrame:
df.to_csv('output.csv', index=False)
>>> groceryDF = pd.read_csv('Grocery.csv')
>>> # Multiplying two Columns to get Total Price for an item
>>> Total = groceryDF['Price'] * groceryDF['Quantity']
>>> # Adding a new Column to the Dataframe
60 Touchpad Informatics Practices-XII

