如何替换Pandas.DataFrame上的整个列

问题描述:

我想将Pandas DataFrame上的整个列替换为另一个DataFrame中的另一列,下面的示例将阐明我要查找的内容

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是

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

现在我有另一个名为df1的数据框,其列"E"为

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

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

,我想用df1的"E"列替换df的"B"列

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

我尝试了多种方式使用.replace()方法,但没有得到任何好处.你能帮我吗?

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

如果您不介意返回新的数据框对象,而不是更新原始的

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'])