Home > Net >  set value to new column according to specific index
set value to new column according to specific index

Time:03-15

I want to create new column name pred_date in df and set value according to specific indexes.

For example for indexes [1, 2, 3] I want to set value as the value in the date column.

df:

    date   label    
1   1.1     1  
2   2.1     0
3   3.1     1 
4   4.1     1

Expected output df:

    date   label    pred_date    
1   1.1     1       1.1 
2   2.1     0       2.1
3   3.1     1       3.1
4   4.1     1       Nan

CodePudding user response:

You could use index.isin where:

df['pred_date'] = df['date'].where(df.index.isin([1,2,3]))

Output:

   date  label  pred_date
1   1.1      1        1.1
2   2.1      0        2.1
3   3.1      1        3.1
4   4.1      1        NaN

CodePudding user response:

Use pd.Series.where:

df['pred'] = df['date'].where(df.index != 4)

Output:

>>> df
   date  label  pred
1   1.1      1   1.1
2   2.1      0   2.1
3   3.1      1   3.1
4   4.1      1   NaN

CodePudding user response:

You can actually just use .loc:

df.loc[[1, 2, 3], 'pred'] = df['date']

Output:

>>> df
   date  label  pred
1   1.1      1   1.1
2   2.1      0   2.1
3   3.1      1   3.1
4   4.1      1   NaN

Or:

df['pred'] = df.loc[[1, 2, 3], 'date']
  • Related