Similar as with() function in R, transform() function provides a way to work on data frame with simplified code inside its block. transform() is mostly used to modify a data frame in a concise and explicit manner. The basic form of usage is transform(df, new_var = operation)
Where
df is the object data frame,
new_var is the variable exist in the resulting data frame,
and operation upon the current variables in the data frame.
In the following example, all the elements of variable ‘age’ in data frame familymember are increased with number 1.
#create a data frame
familymember <- data.frame( name=c("Wilson","Dudu","Maomao","Miaomiao","Mico","Mia"),
age=c(32,20,22, 12,8,3))
#show data frame
familymember
#output
name age
1 Wilson 32
2 Dudu 20
3 Maomao 22
4 Miaomiao 12
5 Mico 8
6 Mia 3
# Apply transform function to increase age with 1
familymember <- transform(familymember, age = age + 1)
#show data frame again
familymember
#output
name age
1 Wilson 33
2 Dudu 21
3 Maomao 23
4 Miaomiao 13
5 Mico 9
6 Mia 4
In the next example of testing grades for students, two new variables, 'total_grade' and 'mean_grade' are created easily with the application of transform() block.
#show first observations of original data frame
head(grade)
#output
StudentID Fullname Race Gender Country Age Math Physics
1 1 James Zhang A Male US 23 73 70
2 2 Wilson Li E Female UK 26 95 76
3 3 Richard Nuan Ye A Male UK 35 77 83
4 4 Mary Deng E Female US 21 60 99
5 5 Jason Wilson A Male UK 19 77 89
6 6 Jennifer Hopkin A Female UK 43 79 64
Chemistry Date
1 87 10/31/2008
2 83 3/16/2008
3 92 5/22/2008
4 84 1/24/2009
5 93 7/30/2009
6 83 4/5/2009
#create two new variables
grade$total_grade <- grade$Math + grade$Physics + grade$Chemistry
grade$mean_grade <- (grade$Math + grade$Physics + grade$Chemistry)/3
#show first observations of data frame again
head(grade)
#output
StudentID Fullname Race Gender Country Age Math Physics
1 1 James Zhang A Male US 23 73 70
2 2 Wilson Li E Female UK 26 95 76
3 3 Richard Nuan Ye A Male UK 35 77 83
4 4 Mary Deng E Female US 21 60 99
5 5 Jason Wilson A Male UK 19 77 89
6 6 Jennifer Hopkin A Female UK 43 79 64
Chemistry Date total_grade mean_grade
1 87 10/31/2008 230 76.66667
2 83 3/16/2008 254 84.66667
3 92 5/22/2008 252 84.00000
4 84 1/24/2009 243 81.00000
5 93 7/30/2009 259 86.33333
6 83 4/5/2009 226 75.33333
Click here to download Python Course Source Files !
For online Python training registration, click here ! Pandas provides flexible ways of generating data…
For online Python training registration, click here ! Data frame is the tabular data object…
Click her for course registration ! When a data frame in Python is created via…
We provide affordable online training course(via ZOOM meeting) for Python and R programming at fundamental…