I want to fill multiple columns with different values.
I have a df that looks as such:
df
'A' 'B' 'C'
0 1 dog red
1 5 cat yellow
2 4 moose blue
I would like to overwrite the columns based upon list values and so would look like this:
overwrite = [0, cat, orange]
df
'A' 'B' 'C'
0 0 cat orange
1 0 cat orange
2 0 cat orange
Is there an easy way to do this?
Thanks
CodePudding user response:
Simply assign the value to the columns, they will be broadcasted:
overwrite = [0, 'cat', 'orange']
df[['A', 'B', 'C']] = overwrite
Or maybe, if the overwrite list can be shorter than the number of columns:
df.iloc[:, :len(overwrite)] = overwrite
# or
df[df.columns[:len(overwrite)]] = overwrite
Output:
A B C
0 0 cat orange
1 0 cat orange
2 0 cat orange
CodePudding user response:
Use DataFrame.assign
with dictionary to overwrite the columns based upon list:
df = df.assign(**dict(zip(df.columns, overwrite)))
print (df)
'A' 'B' 'C'
0 0 cat orange
1 0 cat orange
2 0 cat orange
Or create DataFrame
by constructor - values are not overwritten, but created new one with same columns and index like original DataFrame:
df = pd.DataFrame([overwrite], index=df.index, columns=df.columns)
print (df)
'A' 'B' 'C'
0 0 cat orange
1 0 cat orange
2 0 cat orange
CodePudding user response:
Try this...
df = pd.DataFrame({'A':[1,2,3],'B':['cat','dog','bird']})
overwrite = [0,'Elk']
for index,row in df.iterrows():
df.iloc[index,:] = overwrite
df