Home > Back-end >  Alternatively assign values to two column
Alternatively assign values to two column

Time:12-31

I have a dataset that looks as follows

    Datetime                Message

0   2021-12-20 09:50:08.819 Current sidewing pressure: 3362 
1   2021-12-20 09:50:08.820 Current sidewing pressure: 3303 
2   2021-12-20 09:50:08.839 Current sidewing pressure: 3398 
3   2021-12-20 09:50:08.839 Current sidewing pressure: 3279 
4   2021-12-20 09:50:08.860 Current sidewing pressure: 3398 
5   2021-12-20 09:50:08.860 Current sidewing pressure: 3303 
6   2021-12-20 09:50:08.879 Current sidewing pressure: 3303 

And I am trying to alternatively assign those values to two new columns called Left and Right.

Something as follows

    Datetime                Message                          Left   Right

0   2021-12-20 09:50:08.819 Current sidewing pressure: 3362  3362
1   2021-12-20 09:50:08.820 Current sidewing pressure: 3303         3303
2   2021-12-20 09:50:08.839 Current sidewing pressure: 3398  3398
3   2021-12-20 09:50:08.839 Current sidewing pressure: 3279         3279
4   2021-12-20 09:50:08.860 Current sidewing pressure: 3398  3398
5   2021-12-20 09:50:08.860 Current sidewing pressure: 3303         3303
6   2021-12-20 09:50:08.879 Current sidewing pressure: 3303  3303

Is there a way I can do that?

CodePudding user response:

You can use iloc[::2] to extract every other value (::2 for even indices values, and 1::2 for odd indices values) and assign to a column:

vals = df.Message.str.extract('(\d )$')
df['Right'] = vals.iloc[::2]
df['Left'] = vals.iloc[1::2]

df
                  Datetime                          Message Right  Left
0  2021-12-20 09:50:08.819  Current sidewing pressure: 3362  3362   NaN
1  2021-12-20 09:50:08.820  Current sidewing pressure: 3303   NaN  3303
2  2021-12-20 09:50:08.839  Current sidewing pressure: 3398  3398   NaN
3  2021-12-20 09:50:08.839  Current sidewing pressure: 3279   NaN  3279
4  2021-12-20 09:50:08.860  Current sidewing pressure: 3398  3398   NaN
5  2021-12-20 09:50:08.860  Current sidewing pressure: 3303   NaN  3303
6  2021-12-20 09:50:08.879  Current sidewing pressure: 3303  3303   NaN
  • Related