根据pandas中另一个dataframe中的相似值填充dataframe中的列

2024-06-02 05:49:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据帧:

   df1                             df2
 №    year                       №    year
 1    2010                      373     
 2    2010                      374
 3    2010                      375
 4    2010                      376
 5    2010                      ...                 
...
372   2017
373   2017
374   2017
375   2017
376   2017
377   2017
...                           
899   2026
900   2026
901   2026

我需要找到df1中df2列“№”中的所有值,并用df1中的值填充df2中的“year”列。 结果应该如下所示:

^{pr2}$

我试着这样做

df2['year'] = np.where(df2['№'] == df1['№'] , 'Insert value from df1['year'], '0')

我第一次尝试插入'1',而不是一年,来检查代码是否正常工作,结果我遇到了这样一个错误

ValueError: Can only compare identically-labeled Series objects

有什么建议吗?在


Tags: 数据代码fromonlyvalue错误npwhere