B['x_set'] = B['x_set'].apply(lambda x: x.split(','))
B = B.explode('x_set')
A.merge(B, left_on=['id','x'], right_on=['id','x_set'])
Out[11]:
id x x_set detail
0 1 a a x
1 2 b b n
2 3 c c j
如果pandas<0.25:
将值转换为列表
获取x的展平列表
使用新列表创建新的数据帧
使用pd.Series.repeat传递id和detail
与A合并(我们可以在这里使用相同的键)
B['x_set'] = B['x_set'].apply(lambda x: x.split(','))
len_set = B['x_set'].apply(len).values
values = B['x_set'].values.flatten().tolist()
flat_results = [item for sublist in values for item in sublist]
new_B = pd.DataFrame(flat_results, columns=['x'])
new_B['id'] = B['id'].repeat(len_set).values
new_B['detail'] = B['detail'].repeat(len_set).values
A.merge(new_B, on=['id','x'])
Out[32]:
id x detail
0 1 a x
1 2 b n
2 3 c j
如果使用
pandas==0.25
,您可以:pd.merge
与如果
pandas<0.25
:pd.Series.repeat
传递id
和detail
相关问题 更多 >
编程相关推荐