Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas - Creating a New Column

Tags:

python

pandas

I have always made new columns in pandas using the following:

df['new_column'] = value

I am using this method, however, am receiving the warning for setting a copy.

What is the way to make a new column without creating a copy?

like image 332
Jeff Saltfist Avatar asked Dec 22 '16 01:12

Jeff Saltfist


People also ask

How do I create a column in Pandas?

Create a new column by assigning the output to the DataFrame with a new column name in between the [] . Operations are element-wise, no need to loop over rows. Use rename with a dictionary or function to rename row labels or column names.

How do I create a new column?

To insert a single column: Right-click the whole column to the right of where you want to add the new column, and then select Insert Columns. To insert multiple columns: Select the same number of columns to the right of where you want to add new ones. Right-click the selection, and then select Insert Columns.

How do I create a new blank column in Pandas?

Use an empty string to create an empty column in a Pandas dataframe. Use the syntax DataFrame[new_column] = "" to create an empty column named new_column in the Dataframe .

How do you create a new column in Pandas using values from other columns?

Using apply() method If you need to apply a method over an existing column in order to compute some values that will eventually be added as a new column in the existing DataFrame, then pandas. DataFrame. apply() method should do the trick.


1 Answers

Try using

df.loc[:,'new column'] = value

As piRSquared comments, dfis probably a copy of another DataFrame and when you set values to df it probably incurs in what is called chain indexing. Refer to pandas docs for further information.

like image 59
Miquel Avatar answered Oct 21 '22 17:10

Miquel