Skip to content Skip to sidebar Skip to footer

Defining A Function For Changing Column Values And Creating New Datasets

I am trying to define a function where it will take a dataframe and change values in a column to create multiple new dataframes. As an example, from df1 looking like: df1: class

Solution 1:

Using np.identity (I changed your column name to class_ so it's not using a protected keyword):

arr = np.identity(len(df1))
arr[arr==0] = -1

dfs = [df1.assign(class_=arr[:, i]) for i in range(len(df1))]

for d in dfs:
    print(d, end='\n\n')

   class_ colB colC
0     1.0   1b   1c
1    -1.0   2b   2c
2    -1.0   3b   3c
3    -1.0   4b   4c
4    -1.0   5b   5c

   class_ colB colC
0    -1.0   1b   1c
1     1.0   2b   2c
2    -1.0   3b   3c
3    -1.0   4b   4c
4    -1.0   5b   5c

   class_ colB colC
0    -1.0   1b   1c
1    -1.0   2b   2c
2     1.0   3b   3c
3    -1.0   4b   4c
4    -1.0   5b   5c

   class_ colB colC
0    -1.0   1b   1c
1    -1.0   2b   2c
2    -1.0   3b   3c
3     1.0   4b   4c
4    -1.0   5b   5c

   class_ colB colC
0    -1.0   1b   1c
1    -1.0   2b   2c
2    -1.0   3b   3c
3    -1.0   4b   4c
4     1.0   5b   5c

Post a Comment for "Defining A Function For Changing Column Values And Creating New Datasets"