[英]Append a dataframe with a column of another dataframe and a constant with Python
Let's take these two dataframes : 让我们看一下这两个数据框:
df1 = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df1
A B
0 1 2
1 3 4
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('CD'))
df2
C D
0 5 6
1 7 8
I would like to add column C of df2 to column A of df1, and to put 9 in column B. To sum up, I would like to have : 我想将df2的C列添加到df1的A列,并将9放置在B列中。总而言之,我想拥有:
df1
df1
A B
0 1 2
1 3 4
2 5 9
3 7 9
I tried numerous things with the append function but didn't succeed to find the right code. 我使用append函数尝试了很多事情,但是没有成功找到正确的代码。 Could you please help me ?
请你帮助我好吗 ?
df1.append(df2.rename(columns={'C':'A'}).drop(columns='D'), ignore_index=True) \
.fillna(9).astype(int)
A B
0 1 2
1 3 4
2 5 9
3 7 9
Another alternative based on @splash58's answer : 基于@ splash58的答案的另一种选择:
df1.append(df2.rename(columns={'C':'A'}).drop(df2.columns.difference(['C']), 1), ignore_index=True,sort=False) \
.fillna(9).astype(int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.