'How do I fill a column with one value in Pandas?
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
Solution 1:[1]
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 2:[2]
You can also exploit the power of the .loc property by addressing all the rows using : as the argument. Say that your DataFrame is called df:
df.loc[:,'A'] = 'foo'
Resulting in
A
0 foo
1 foo
2 foo
3 foo
Solution 3:[3]
You can use the method assign:
df = df.assign(A='foo')
Solution 4:[4]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mm_ |
| Solution 2 | |
| Solution 3 | |
| Solution 4 | U12-Forward |
