应用中的交叉引用 pandas 数据框

crossreferencing pandas dataframe in apply

所以我有一些数据,例如:

a.csv:

id, ..., name
1234, ..., R
1235, ..., Python
1236, ..., Panda
... etc

b.csv:

id, ..., amount
1234, ..., 1
1234, ..., 1
1234, ..., 2
...
1236, ..., 1
1236, ..., 1

我正在尝试交叉引用 a.csv 和 b.csv 之间的 ID,以便将数量列添加到 a.csv 的 pandas 数据框。这个数量是"the sum of amounts in b.csv for the matching ID of this row".

我正在尝试像这样使用应用函数:

  import pandas as pd
  def itemcounts(row):
      # ok this works?
      # return b[b['id'] == 1234]['amount'].sum()
      # each a['quantity'] gets set to 4 or whatever the sum for 1234 is.

      # and this does?
      # return row['id']
      # a['quantity'] get set to whatever row's 'id' is.

      # but this doesn't
      id = row['id']
      return b[b['id'] == id]['amount'].sum()
      # a['quantity'] is 0.

  a = pd.read_csv('a.csv')
  b = pd.read_csv('b.csv')
  a['quantity'] = a.apply(itemcounts, axis=1)

但如评论中所述,我无法申请在 b 中查找匹配行以获取总和。我想我在这里遗漏了 python 或 pandas 的一些基本内容。

我尝试将 row['id'] 转换为 itemcounts 中的 int,但这对我来说仍然没有用。

试试这个:

df = pd.DataFrame({'id' : [1234, 1235, 1236], 'name' : ['R', 'Python', 'Pandas']})

     id    name
0  1234       R
1  1235  Python
2  1236  Pandas

df1 = pd.DataFrame({'id' : [1234, 1234, 1234, 1234, 1234, 1235, 1235, 1236], 'amount' : [1, 1, 2, 1, 2, 2, 1, 1]})

   amount    id
0       1  1234
1       1  1234
2       2  1234
3       1  1234
4       2  1234
5       2  1235
6       1  1235
7       1  1236

df['quantity'] = df1.groupby('id').agg(sum).values

     id    name  quantity
0  1234       R         7
1  1235  Python         3
2  1236  Pandas         1

这个脚本对我有用:

import pandas as pd
a = pd.read_csv('a.csv')
b = pd.read_csv('b.csv')

a['Quantity'] = a['id'].apply(lambda x: b[b.id == x].amount.sum())

在应用函数中使用 "lambda" 允许您将列的每一行应用到一个函数中作为 "x"。

拍摄:

    id    name
0  1234       r        
1  1235  Python       
2  1236   Panda

和乙:

     id  amount   
0  1234       1
1  1234       1
2  1234       2
3  1236       1
4  1236       1

它returns:

        id    name  Quantity
0     1234       r         4
1     1235  Python         0
2     1236   Panda         2