Home > Software design >  How to create a new column from dataframe based on a given condition
How to create a new column from dataframe based on a given condition

Time:10-11

I would like to create a new column target based on the values on the source column. I simply want to assign values from this list [6,7,8,9,10,11,12,13] to the rows of the source column

   value    source
0   0.83    0
1   0.99    0
2   0.20    0
3   0.79    0
4   0.19    0
5   0.86    0
6   0.31    1
7   0.19    1
8   0.50    2
9   0.44    2
10  1.00    2
11  0.67    2
12  0.74    3
13  0.43    3
14  0.21    3
15  0.03    4
16  1.00    4
17  0.57    4
18  0.67    5
19  1.00    5

expected output

   value    source   target
0   0.83    0           6
1   0.99    0           7
2   0.20    0           8
3   0.79    0           9
4   0.19    0           10
5   0.86    0           11
6   0.31    1           6
7   0.19    1           7
8   0.50    2           6
9   0.44    2           7
10  1.00    2           8
11  0.67    2           9
12  0.74    3           6
13  0.43    3           7
14  0.21    3           8
15  0.03    4           6
16  1.00    4           7
17  0.57    4           8
18  0.67    5           6
19  1.00    5           7

CodePudding user response:

Use GroupBy.cumcount with mapping by dictioanry created from list with enumerate:

L = [6,7,8,9,10,11,12,13] 
df['target'] = df.groupby('source').cumcount().map(dict(enumerate(L)))
print (df)
    value  source  target
0    0.83       0       6
1    0.99       0       7
2    0.20       0       8
3    0.79       0       9
4    0.19       0      10
5    0.86       0      11
6    0.31       1       6
7    0.19       1       7
8    0.50       2       6
9    0.44       2       7
10   1.00       2       8
11   0.67       2       9
12   0.74       3       6
13   0.43       3       7
14   0.21       3       8
15   0.03       4       6
16   1.00       4       7
17   0.57       4       8
18   0.67       5       6
19   1.00       5       7
  • Related