Methods for Data Transformation
Sometimes we do not just want to view the data. We want to change or transform it.
apply(): The apply() method applies a function to each value of the Series.
For example, suppose we want to add 5 marks to every student's marks:
marks = pd.Series([70, 80, 90])
marks.apply(lambda x: x + 5)
output:
0 75
1 85
2 95
dtype: int64
Here, the function is applied to each value one by one.
map(): The map() method is used to map or transform values using a function, dictionary, or another Series.
For example:
marks = pd.Series([90, 80, 70])
90: "A",
80: "B",
70: "C"
})
output:
0 A
1 B
2 C
dtype: object
Here, each mark is mapped to a grade according to the given dictionary.
replace(): The replace() method replaces specific values with other values.
For example:
marks = pd.Series([80, 0, 90, 0])
marks.replace(0, 50)
output:
0 80
1 50
2 90
3 50
dtype: int64
Here, every 0 in the Series is replaced with 50.
astype(): The astype() method converts the Series into another data type.
For example:
marks = pd.Series([85, 72, 90])
marks.astype(float)
output:
0 85.0
1 72.0
2 90.0
dtype: float64
Here, the values are converted into the float data type.
round(): The round() method rounds numerical values to the specified number of decimal places.
For example:
marks = pd.Series([85.678, 72.456, 90.123])
marks.round(2)
output:
0 85.68
1 72.46
2 90.12
dtype: float64
Here, the values are rounded to 2 decimal places.
clip(): The clip() method limits values within a specified minimum and maximum range.
For example:
marks = pd.Series([30, 50, 75, 95])
marks.clip(40, 90)
output:
0 40
1 50
2 75
3 90
dtype: int64
Here:
Values below 40 become 40
Values above 90 become 90
Values between 40 and 90 remain unchanged