1

I would like to iterate over the columns and change the content of the columns with the assign function.

Related to this problem

So in that example they show that you can use the assign function:

df = df.assign(industry='yyy')

To change the content of the column called industry.

I thought I could perform:

for column in df.columns[1:]:
     df = df.assign(column='yyy')

But now a new column with the label column is created, instead of all columns obtaining 'yyy' as content.

Sanji1P
  • 53
  • 6

1 Answers1

2

The following snippet will do what you expect :-)

# Option 1

for col in df.columns:
     df.loc[:, col] = 'yyy'

# Option 2 (with .assign())

cols = {col: 'yyy' for col in df.columns}
df = df.assign(**cols)

Input:

enter image description here

Output:

enter image description here

ggeop
  • 1,230
  • 12
  • 24