How to put a parameter in the assign function of DataFrames?

Question:

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.

Asked By: Sanji1P

||

Answers:

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

Answered By: ggeop
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.