Reputation: 9335
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!
Upvotes: 1
Views: 147
Reputation: 71570
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
Upvotes: 1
Reputation: 323226
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
Upvotes: 3
Reputation: 51335
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
Upvotes: 1