我正在寻找连接 2 个数据框的方法,并在值不可用的地方填充值。
在此示例中,我有第一个数据帧 input1,其中包含所有字段的数据。我正在尝试使用此数据帧并填充/连接第二个数据帧 input2 并生成输出数据帧。
dataframe1 中的 row1 可以通过匹配 Age 列并填充 Name 列来与 row2 连接。 dataframe1 中的 row2 可以通过填充 dataframe1 中的“Name”和“Age”列来与 row2 连接。 dataframe1 中的 row1 也可以通过填充 dataframe1 中的“Name”和“Age”列来与 row2 连接。
Name Age Courses
0 Tom 20 Math
1 Nick 21 Science
Name Age Fees
0 NaN 20.0 100
1 NaN NaN 200
Name Age Courses Fees
0 Tom 20 Math 100
1 Nick 21 Science 200
2 Tom 20 Math 200
input1 = pd.DataFrame({
'Name': ['Tom', 'Nick'],
'Age': [20, 21],
'Courses': ['Math', 'Science']
})
input2 = pd.DataFrame({
'Name': [np.NaN, np.NaN],
'Age': [20, np.NaN],
'Fees': [100, 200]
})
output = pd.DataFrame({
'Name': ['Tom', 'Nick', 'Tom'],
'Age': [20, 21, 20],
'Courses': ['Math', 'Science', 'Math'],
'Fees': [100, 200, 200]
})
代码
一种可能的方法是使用 pandas
merge
函数与 cross join
创建笛卡尔积,然后仅过滤满足条件的行(请注意,如果数据很大,交叉连接效率很低)。
# Define columns to be compared to variable cols.
cols = ['Name', 'Age']
# Perform a cross join between input1 and input2
tmp = input1.merge(input2, how='cross', suffixes=['', '_y'])
# Filter out the columns which have the '_y' suffix
tmp2 = tmp.filter(like='_y').set_axis(cols, axis=1)
# Create condition
cond = (tmp[cols].eq(tmp2) | tmp2.isna()).all(axis=1)
# filter
out = tmp.loc[cond, tmp.columns[~tmp.columns.str.contains('_y')]]
出
Name Age Courses Fees
0 Tom 20 Math 100
1 Tom 20 Math 200
3 Nick 21 Science 200