Reputation: 3392
I need to add columns to the DataFrame df
. The values for all new columns should be fixed along all rows of df
:
df = {
"NUM":[1,2],
"WAKE":["M","H"],
"DISTANCE":[780,500]
}
new_df = pd.DataFrame(df)
This is how I tried to add new multiple columns with fixed values.
for column, row in new_df.iterrows():
row["TEMPERATURE"] = 20
row["VISIBILITY"] = 5000
row["WIND"] = 10
This code does not fail, but new columns are not created.
The expected result:
NUM WAKE DISTANCE TEMPERATURE VISIBILITY WIND
1 M 780 20 5000 10
2 H 500 20 5000 10
Upvotes: 3
Views: 1136
Reputation: 182
I had the same problem before trying to change values through iterrows. I realized that if you don't actually call your variable/data frame when making the change, you're not changing anything. I don't know the reasoning behind it, but for it to work you have to use .loc[column,column name] to make the actual change.
for column, row in new_df.iterrows():
new_df.loc[column,"TEMPERATURE"] = 20
new_df.loc[column,"VISIBILITY"] = 5000
new_df.loc[column,"WIND"] = 10
Upvotes: 1
Reputation: 385
Easy enough!
new_df['TEMPERATURE'] = 20
new_df['VISIBILITY'] = 5000
new_df['WIND'] = 10
and will yield:
INDEX NUM WAKE DISTANCE TEMPERATURE VISIBILITY WIND
0 1 M 780 20 5000 10
1 2 H 500 20 5000 10
This way you define the new columns for the dataframe and set each row value to the single value
Upvotes: 2
Reputation: 323316
Two steps
adddf=pd.DataFrame({'TEMPERATURE': 20, 'VISIBILITY': 5000, 'WIND': 10},index=new_df.index)
pd.concat([new_df,adddf],1)
Out[253]:
DISTANCE NUM WAKE TEMPERATURE VISIBILITY WIND
0 780 1 M 20 5000 10
1 500 2 H 20 5000 10
Upvotes: 2
Reputation: 402813
This is as simple as a single assign
call with a dictionary:
dct = {'TEMPERATURE': 20, 'VISIBILITY': 5000, 'WIND': 10}
new_df2 = new_df.assign(**dct)
new_df2
NUM WAKE DISTANCE TEMPERATURE VISIBILITY WIND
0 1 M 780 20 5000 10
1 2 H 500 20 5000 10
Upvotes: 5