1

I have a Pandas dataframe, old, like this:

  col1 col2 col3
0   1   2   3
1   2   3   4
2   3   4   5

I want to make a new dataframe, new, that copies col2 from old and fills in -1 as dummy values for its other columns:

  col2 new_col1 new_col3
0   2   -1       -1
1   3   -1       -1
2   4   -1       -1

I suppose I could do iterate row by row and fill in -1 for any column not in old but figure there must be a better, likely vectorized way.

Ideas?

Thanks!

4 Answers 4

3

You can do reindex .

df.reindex(columns=['col2','newcol1','newcol3'],fill_value=-1)
Out[183]: 
   col2  newcol1  newcol3
0     2       -1       -1
1     3       -1       -1
2     4       -1       -1
Sign up to request clarification or add additional context in comments.

1 Comment

Where do you specify the value for columns that aren't in old?
2

assign

df[['col2']].assign(new_col1=-1, new_col3=-1)

Comments

1

IIUC:

new = old.copy()
new[['col1','col3']] = -1

>>> new
   col1  col2  col3
0    -1     2    -1
1    -1     3    -1
2    -1     4    -1

Or more generally, to change all columns besides col2 to -1:

new = old.copy()
new[list(set(new.columns) - {'col2'})] = -1

Comments

1

Maybe:

new=pd.DataFrame({'col2':old['col2'],'new_col2':-1,'new_col3':-1})
print(new)

Output:

   col2  new_col2  new_col3
0     2        -1        -1
1     3        -1        -1
2     4        -1        -1

@sacul Thanks for telling me

1 Comment

No need to do [-1]*3: new=pd.DataFrame({'col2':old['col2'],'new_col2':-1,'new_col3':-1})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.