gpt4 book ai didi

python - 如何通过字符串包含合并基于两列的 2 个数据帧

转载 作者:行者123 更新时间:2023-12-04 09:56:05 24 4
gpt4 key购买 nike

我的问题有点类似于这个:How to merge pandas on string contains? ,但我需要不同的输出,而且问题本身有点复杂。所以我有 2 个类似于下面的数据帧:

df1 = pd.DataFrame({'ref_name':['city-louisville','city-louisville','city-louisville', 'town-lexington','town-lexington','town-lexington'], 'un_name1':['CPU1','CPU2','GPU1','CPU1','CPU2','GPU1'], 'value1':[10,15,28,12,14,14]})

df2 = pd.DataFrame({'ref_name':['louisville','louisville','lexington','lexington'], 'un_name2':['CPU','GPU','CPU','GPU'], 'value2':[25,28,26,14]})

我需要加入基于 ref_nameun_name基于其中的子字符串。它们不会总是像这样干净,但我认为这是一个不错的小例子。所以在这种情况下我想要的输出看起来像这样:
ref_name  |  un_name1  |  un_name2  | value1  |  value2
---------------------------------------------------------
louisville| CPU1 | CPU | 10 | 25
louisville| CPU2 | CPU | 15 | 25
louisville| GPU1 | GPU | 28 | 28
lexington | CPU1 | CPU | 12 | 26
lexington | CPU2 | CPU | 14 | 26
lexington | GPU1 | GPU | 14 | 14

在此先感谢您对此的任何帮助!

最佳答案

这是我能想到的最通用的版本。如果您的数据框很大,则性能可能是一个问题。

mask1 = df2['ref_name'].apply(lambda value: df1['ref_name'].str.contains(value))
mask2 = df2['un_name2'].apply(lambda value: df1['un_name1'].str.contains(value))
mask = (mask1 & mask2).stack().rename_axis(['index2', 'index1'])
mask = mask[mask].index.to_frame(False)

result = mask.merge(df2, left_on='index2', right_index=True) \
.merge(df1, left_on='index1', right_index=True)

结果:
 index2  index1  ref_name_x un_name2  value2       ref_name_y un_name1  value1
0 0 louisville CPU 25 city-louisville CPU1 10
0 1 louisville CPU 25 city-louisville CPU2 15
1 2 louisville GPU 28 city-louisville GPU1 28
2 3 lexington CPU 26 town-lexington CPU1 12
2 4 lexington CPU 26 town-lexington CPU2 14
3 5 lexington GPU 14 town-lexington GPU1 14

修剪/重命名列是留给 OP 的练习。

关于python - 如何通过字符串包含合并基于两列的 2 个数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61923291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com