【问题标题】:How to add a column to a dataframe from another dataframe with different size如何从具有不同大小的另一个数据框将列添加到数据框
【发布时间】:2019-10-19 22:32:17
【问题描述】:

我有 2 个数据框,我想从另一个数据框向我的一个数据框添加一个新列 '''

(df1)                            
Id   height  ...                 
12   190
13   180
34   173

。 . .

(df2)
Id     amount  ...
12      234
15      256
13      248

。 . .

''' 如何向 df1 添加一列“数量”,其中包含 df1 的每个 Id 的 df2 的值数量。 df1 和 df2 的大小不相等

【问题讨论】:

  • df.join(df1.set_index('Id'), on='Id')

标签: python pandas dataframe


【解决方案1】:

您可以在Id 列上merge 两个DataFrame,然后将生成的amount 列分配给您的第一个df:

import pandas as pd

df1 = pd.DataFrame(
    {"Id": [12, 13, 34], "height": [1, 2, 3]}
)
df2 = pd.DataFrame(
    {"Id": [12, 15, 13], "amount": [4, 5, 6]}
)

df1["amount"] = df1.merge(df2, on="Id")["amount"]

结果:

>>> print(df1)

   Id  height  amount
0  12       1     4.0
1  13       2     6.0
2  34       3     NaN

【讨论】:

    【解决方案2】:

    Id Id 是索引列,然后你可以使用更新方法来做到这一点

    df1 = pd.DataFrame([[12, 190.0], [13, 180.0], [34, 173.0]], columns=('Id', 'height')).set_index("Id")
    
    df2 = pd.DataFrame([[12, 234.0], [15, 256.0], [13, 248.0]], columns=('Id', 'amount')).set_index("Id")
    
    df1["amount"] = np.nan
    df1.update(df2, overwrite=True)
    print(df1)
    

    结果

        height  amount
    Id                
    12   190.0   234.0
    13   180.0   248.0
    34   173.0     NaN
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      • 2016-02-03
      • 2018-01-14
      • 1970-01-01
      相关资源
      最近更新 更多