【问题标题】:How to efficiently join a small table to a large one on python如何有效地将小表连接到python上的大表
【发布时间】:2022-06-24 20:53:08
【问题描述】:

我有两个类似的表:

df_1 = pd.DataFrame({'id': [1,1,1,1,1,2,2,2,2,2], 'x': [0,1,2,3,4,5,6,7,8,9]})

   id  x
0   1  0
1   1  1
2   1  2
3   1  3
4   1  4
5   2  5
6   2  6
7   2  7
8   2  8
9   2  9

df_2 = pd.DataFrame({'y': [10,100]}, index=[1,2])

     y
1   10
2  100

我的目标是在id 的基础上将df['x'] 乘以df['y']。我目前的解决方案有效,但在我看来应该有一种更有效/更优雅的方式来做到这一点。

这是我的代码:

df_comb = pd.merge(df_1, df_2, left_on='id', right_index=True)
x_new = df_comb['x'] * df_comb['y']
df_1['x_new'] = x_new.to_numpy()

   id  x  x_new
0   1  0      0
1   1  1     10
2   1  2     20
3   1  3     30
4   1  4     40
5   2  5    500
6   2  6    600
7   2  7    700
8   2  8    800
9   2  9    900

【问题讨论】:

    标签: python pandas merge


    【解决方案1】:

    你可以使用:

    df_1['x_new'] = df_1['id'].map(df_2['y']).mul(df_1['x'])
    

    输出:

       id  x  x_new
    0   1  0      0
    1   1  1     10
    2   1  2     20
    3   1  3     30
    4   1  4     40
    5   2  5    500
    6   2  6    600
    7   2  7    700
    8   2  8    800
    9   2  9    900
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      • 2020-09-05
      • 1970-01-01
      相关资源
      最近更新 更多