[英]How to append a column to a DataFrame that collects values of another DataFrame in Python?
[英]Append a dataframe with a column of another dataframe and a constant with Python
讓我們看一下這兩個數據框:
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
我想將df2的C列添加到df1的A列,並將9放置在B列中。總而言之,我想擁有:
df1
df1
A B
0 1 2
1 3 4
2 5 9
3 7 9
我使用append函數嘗試了很多事情,但是沒有成功找到正確的代碼。 請你幫助我好嗎 ?
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
基於@ 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.