Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace an entire column on Pandas.DataFrame

Tags:

python

pandas

I would like to replace an entire column on a Pandas DataFrame with another column taken from another DataFrame, an example will clarify what I am looking for

import pandas as pd dic = {'A': [1, 4, 1, 4], 'B': [9, 2, 5, 3], 'C': [0, 0, 5, 3]} df = pd.DataFrame(dic) 

df is

'A' 'B' 'C'  1   9   0  4   2   0  1   5   5  4   3   3 

Now I have another dataframe called df1 with a column "E" that is

df1['E'] = [ 4, 4, 4, 0] 

and I would like to replace column "B" of df with column "E" of df1

'A' 'E' 'C'  1   4   0  4   4   0  1   4   5  4   0   3 

I tried to use the .replace() method in many ways but I didn't get anything good. Can you help me?

like image 473
Stefano Fedele Avatar asked Apr 25 '16 16:04

Stefano Fedele


People also ask

How do I replace in pandas?

Pandas DataFrame replace() MethodThe replace() method replaces the specified value with another specified value. The replace() method searches the entire DataFrame and replaces every case of the specified value.

How do I replace multiple columns in pandas?

Pandas replace multiple values in column replace. By using DataFrame. replace() method we will replace multiple values with multiple new strings or text for an individual DataFrame column. This method searches the entire Pandas DataFrame and replaces every specified value.

How do I change the value of a DataFrame in Python?

You can change the values using the map function. This way you map each column of your dataframe.


2 Answers

If the indices match then:

df['B'] = df1['E'] 

should work otherwise:

df['B'] = df1['E'].values 

will work so long as the length of the elements matches

like image 109
EdChum Avatar answered Oct 08 '22 16:10

EdChum


If you don't mind getting a new data frame object returned as opposed to updating the original Pandas .assign() will avoid SettingWithCopyWarning. Your example:

df = df.assign(B=df1['E']) 
like image 32
jedge Avatar answered Oct 08 '22 17:10

jedge