How do I fill a column with one value in Pandas?

PythonPandas

Python Problem Overview


I have a column with consecutive digits in a Pandas DataFrame.

A
1
2
3
4

I would like to change all those values to a simple string, say "foo", resulting in

A
foo
foo
foo
foo

Python Solutions


Solution 1 - Python

Just select the column and assign like normal:

In [194]:
df['A'] = 'foo'
df

Out[194]:
     A
0  foo
1  foo
2  foo
3  foo

Assigning a scalar value will set all the rows to the same scalar value

Solution 2 - Python

The good answer above throws a warning. You can also do:

df.insert(0, 'A', 'foo')

where 0 is the index where the new column will be inserted.

Solution 3 - Python

You can also exploit the power of the .loc property by addressing all the rows using : as the argument to address the rows.

Say that your DataFrame is called df:

In [1]:
df.loc[:,'A'] = 'foo'
df

Out [2]:
     A
0  foo
1  foo
2  foo
3  foo

Solution 4 - Python

You can use the method assign:

df = df.assign(A='foo')

Solution 5 - Python

You could also try pd.Series.replace:

df['A'] = df['A'].replace(df['A'], 'foo')
print(df)

Output:

     A
0  foo
1  foo
2  foo
3  foo

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDervin ThunkView Question on Stackoverflow
Solution 1 - PythonEdChumView Answer on Stackoverflow
Solution 2 - Pythonmm_View Answer on Stackoverflow
Solution 3 - PythonMarioanzasView Answer on Stackoverflow
Solution 4 - PythonMykola ZotkoView Answer on Stackoverflow
Solution 5 - PythonU12-ForwardView Answer on Stackoverflow