I have a data frame (df) with 7 rows and 4 columns (named c1, c2, c3, c4):
c1 c2 c3 c4
Yes No Yes No
Yes Yes No No
No Yes No No
Yes No No No
Yes No Yes No
Yes No No No
No No Yes No
I want to add a 5th column to the data frame named Expected Result if the values on columns 1 to 4 are equal to "Yes". For example, on row 1, I have "Yes" parameters in Column 1 and Column 3. To populate Expected Result column, I would concatenate and add Column1 name and Column 2 name to the result.
Here is the full results expected:
c1, c3
c1, c2
c2
c1
c1, c3
c1
c3
I have the following line of code but something is not quite right:
df$Expected_Result <- colnames(df)[apply(df,1,which(LETTERS="Unfit"))]
You can use the loc and iloc functions to access columns in a Pandas DataFrame. Let's see how. If we wanted to access a certain column in our DataFrame, for example the Grades column, we could simply use the loc function and specify the name of the column in order to retrieve it.
If you wanted to get a specific cell value from the last Row of Pandas DataFrame, use the negative index to point the rows from last. For example, Index -1 represents the last row and -2 for the second row from the last. Similarly, you should also use -1 for the last column.
An option using data.table
library(data.table)
setDT(df)[, rownum:=1:.N,]
df$Expected_result <- melt(df, "rownum")[,
toString(variable[value=="Yes"]), rownum]$V1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With