所以我有一些数据,比如:
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,但仍然没有成功。你知道吗
试试这个:
这个剧本对我很有用:
在apply函数中使用“lambda”可以将列的每一行作为“x”应用到函数中。你知道吗
采取行动:
和b:
它返回:
相关问题 更多 >
编程相关推荐