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?
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.
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.
You can change the values using the map function. This way you map each column of your dataframe.
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
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With