所以我有一些数据:
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或pandas的基本内容。
我尝试在项目计数中将row['id']
转换为int,但这对我来说仍然没有用。
答案 0 :(得分: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
答案 1 :(得分:0)
这个脚本对我有用:
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