Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 
like image 862
Dervin Thunk Avatar asked Jan 15 '16 13:01

Dervin Thunk


People also ask

How do I fill a specific value in pandas?

Pandas DataFrame fillna() MethodThe fillna() method replaces the NULL values with a specified value. The fillna() method returns a new DataFrame object unless the inplace parameter is set to True , in that case the fillna() method does the replacing in the original DataFrame instead.

How do you fill a column with one value?

Press "Ctrl-Enter" on the keyboard. Excel fills the other cells in the column with the same value.

How do I assign a value to a column in pandas?

You can set cell value of pandas dataframe using df.at[row_label, column_label] = 'Cell Value'. It is the fastest method to set the value of the cell of the pandas dataframe. Dataframe at property of the dataframe allows you to access the single value of the row/column pair using the row and column labels.

How do you fill a column of a DataFrame in Python?

Fill Data in an Empty Pandas DataFrame by Appending Rows First, create an empty DataFrame with column names and then append rows one by one. The append() method can also append rows. When creating an empty DataFrame with column names and row indices, we can fill data in rows using the loc() method.


2 Answers

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

like image 62
EdChum Avatar answered Sep 23 '22 13:09

EdChum


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.

like image 37
mm_ Avatar answered Sep 19 '22 13:09

mm_