![](/img/trans.png)
[英]Pandas: Filling column in dataset with data from another dataset based on matching columns in the two datasets
[英]Extract values of two columns from a dataset based on the column's value of another dataset
我试图根据另一个数据集的列值从数据集中提取两列的值。
例子:
df1:
index ID Value
0 45 04
1 32 03
2 34 08
3 6 05
4 45 04
df2
index ID Weight Height
0 6 50 155
1 32 55 164
2 34 66 162
3 45 54 163
4 99 55 155
我想得到:
df1
index ID Value Weight Height
0 45 04 54 163
1 32 03 55 164
2 34 08 66 162
3 6 05 50 155
4 45 04 54 163
我试过了:
pd.merge(df1, df2, on="id")
但它给了我一个比 df1 更大的数据集。
谢谢你。
您可以随心所欲,只需删除一个额外的列:
(pd.merge(df1, df2, on="ID", suffixes=('', '_y'))
.drop('index_y', axis=1)
.sort_values('index')
)
输出:
index ID Value Weight Height
0 45 4 54 163
1 32 3 55 164
2 34 8 66 162
3 6 5 50 155
4 45 4 54 163
使用左连接并避免重复通过DataFrame.drop_duplicates
从df2
删除它们:
pd.merge(df1, df2.drop_duplicates('ID'), on="ID", how='left')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.