应用中的交叉引用数据帧

2024-10-01 19:30:22 发布

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

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

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数据帧中。此数量是“此行匹配ID的b.csv中的金额总和”。你知道吗

我试着像这样使用apply函数:

  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或熊猫在这里。你知道吗

我尝试在itemcounts中将row['id']强制转换为int,但仍然没有成功。你知道吗


Tags: csv数据idpandas数量returnisthis
2条回答

试试这个:

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())

在apply函数中使用“lambda”可以将列的每一行作为“x”应用到函数中。你知道吗

采取行动:

    id    name
0  1234       r        
1  1235  Python       
2  1236   Panda

和b:

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

它返回:

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

相关问题 更多 >

    热门问题