【问题标题】:Adding a new column in one DataFrame where values are based from a second DataFrame在一个 DataFrame 中添加一个新列,其中值基于第二个 DataFrame
【发布时间】:2022-11-21 00:00:02
【问题描述】:

我有两个DataFrame,df_a就是我们要操作的DataFrame。我想添加一个新列,但在具有相似列名的第二个 DataFrame 中找到了这些值。

让我解释一下。

df_a包含

_ | Code | Speed | Velocity |
0 |  DA  |   23  |    22    |
1 |  ES  |   23  |    22    |
2 |  DA  |   23  |    22    |
3 |  GA  |   23  |    22    |
4 |  NU  |   23  |    22    |

df_b包含

_ | Code |     Name    |
0 |  DA  |   DinoAero  |
1 |  ES  |    Espeed   |
2 |  GA  |    GeoArk   |
3 |  NU  |  NewUnicorn |

我想合并或连接这两个数据帧,结果应如下所示:

_ | Code |     Name     | Speed | Velocity |
0 |  DA  |   DinoAero   |   23  |    22    |
1 |  ES  |    Espeed    |   23  |    22    |
2 |  DA  |   DinoAero   |   23  |    22    |
3 |  GA  |    GeoArk    |   23  |    22    |
4 |  NU  |  NewUnicorn  |   23  |    22    | 

我对 Python 和 Pandas 都很陌生,我也很难找到合适的问题,所以我决定在 stackoverflow 中提问,冒着投反对票的风险让我学习。感谢每个愿意分享智慧的耐心。

【问题讨论】:

    标签: python pandas dataframe jupyter-notebook


    【解决方案1】:

    您只想 pd.merge()(类似于 SQL 连接)。

    在你的情况下:

    new_df = pd.merge(df_a,df_b,how='left',on='Code')
    new_df = new_df[['Code','Name','Speed','Velocity']] # if you want to re-arrange the columns in your order
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-07
      • 2016-05-26
      • 1970-01-01
      • 2020-10-16
      • 2016-03-22
      • 1970-01-01
      • 2021-05-11
      相关资源
      最近更新 更多