0

I have a data frame which has 4 columns.

A.        B.        C.        D
1.        2.        4.        86
1.        2.        4.        97
1.        2.        4.        49
3.        6.        9.        78
3.        6.        9.        65
3.        6.        9.        45

The rows with same values in columns A B and C should create multiple columns D (D1, D2, D3) and stack the row wise values of D in D1, D2 and D3 in same row.

I want the output like this

A.     B.     C.     D1.    D2.   D3 
1.     2.     4.     86.    97.   49
3.     6.     9.     78.    65.   45. 
Naveed
  • 11,495
  • 2
  • 14
  • 21

1 Answers1

0

So are you trying to replace values based on condition? You can use the dataframe.loc[] function

  1. df.loc[ df[“column_name”] == “some_value”, “column_name”] = “value”
  2. some_value = The value that needs to be replaced
  3. value = The value that should be placed instead.

example:

Importing the libraries
import pandas as pd
import numpy as np
  
# data
Student = {
    'Name': ['John', 'Jay', 'sachin', 'Geetha', 'Amutha', 'ganesh'],
    'gender': ['male', 'male', 'male', 'female', 'female', 'male'],
    'math score': [50, 100, 70, 80, 75, 40],
    'test preparation': ['none', 'completed', 'none', 'completed',
                         'completed', 'none'],
}
  
# creating a Dataframe object
df = pd.DataFrame(Student)
  
# Applying the condition
df.loc[df["gender"] == "male", "gender"] = 1