Split Dataframe by Cut-off, assign 1 vs 0 in a new column

Viewed 27

I have a dataset(df) that looks a follows:

enter image description here

I have split df by the miR21 cutoff of 8 in dfn21h (>= 8) and dfn21l (< 8).

Now I want to split df by the cutoff of 8 (miR21) and ad a new column ('group') to my dataset with 1 for >= 8 and 0 for < 8.

What is the best way to do this?

1 Answers

First create your column (col), change its type to int (since you want 1, 0 in your post), then add it to the data frame. There are probably more compact ways to do this, but this should work.

col = df['miR21'] > 8
col.name = 'group'
df['group'] = col.astype(int)

Update: to use a general name instead, do this:

newcol = [ 'control' ] * len(df) # Create a new column that's all 'control'
df['group'] = newcol
df.loc[df['miR21'] > 8, 'group'] = 'test' 

The last line says, if df['miR21'] > 8, then change the 'group' value to 'test'

Related