我想合并两个熊猫数据框,并希望基于两列进行合并。
代码如下:
import numpy as np
import pandas as pd
from itertools import product
# first dataframe
data = np.array([[1, 1, 6],
[1, 2, 2],
[2, 1, 1],
[2, 2, 9],
[3, 1, 1],
[3, 2, 1]])
df = pd.DataFrame(data, columns=['x','y','z'])
print(df)
x y z
0 1 1 6
1 1 2 2
2 2 1 1
3 2 2 9
4 3 1 1
5 3 2 1
## another dataframe
N = 4
perms = list(product(range(N), range(N)))
x = [i[0] for i in perms]
y = [i[1] for i in perms]
df1 = pd.DataFrame({'x': x,'y': y,'z':0})
print(df1)
输出应如下所示:
x y z
0 0 0 0
1 0 1 0
2 0 2 0
3 0 3 0
4 1 0 0
5 1 1 6
6 1 2 2
7 1 3 0
8 2 0 0
9 2 1 1
10 2 2 9
11 2 3 0
12 3 0 0
13 3 1 1
14 3 2 1
15 3 3 0
问题 如何从数据帧df更新df1的z列的值?
答案 0 :(得分:1)
首先merge
,然后update
df1.update(df1.drop('z',1).merge(df,how='left'))
df1
Out[439]:
x y z
0 0 0 0.0
1 0 1 0.0
2 0 2 0.0
3 0 3 0.0
4 1 0 0.0
5 1 1 6.0
6 1 2 2.0
7 1 3 0.0
8 2 0 0.0
9 2 1 1.0
10 2 2 9.0
11 2 3 0.0
12 3 0 0.0
13 3 1 1.0
14 3 2 1.0
15 3 3 0.0