如何按条件将DataFrame2指定列匹配添加至DataFrame1?
条件匹配合并DataFrame列
需求:将两个独立的DataFrame合并,仅当第一个DataFrame的descriptor列值为'red',且date、product列与第二个DataFrame对应匹配时,才将第二个DataFrame的val列值填充到第一个DataFrame中。
原始DataFrame
DataFrame 1
date product descriptor jan product1 blue feb product2 green mar product1 red apr product2 blue may product1 red jun product2 red
DataFrame 2
date product val mar product1 x may product1 y jun product2 z
期望结果
date product descriptor val jan product1 blue feb product2 green mar product1 red x apr product2 blue may product1 red y jun product2 red z
解决方法
可以通过pandas的合并操作结合条件筛选实现,以下提供两种方案:
方案1:使用apply逐行判断
import pandas as pd # 构造原始DataFrame df1 = pd.DataFrame({ 'date': ['jan', 'feb', 'mar', 'apr', 'may', 'jun'], 'product': ['product1', 'product2', 'product1', 'product2', 'product1', 'product2'], 'descriptor': ['blue', 'green', 'red', 'blue', 'red', 'red'] }) df2 = pd.DataFrame({ 'date': ['mar', 'may', 'jun'], 'product': ['product1', 'product1', 'product2'], 'val': ['x', 'y', 'z'] }) # 左连接获取val列 merged_df = df1.merge(df2, on=['date', 'product'], how='left') # 仅保留descriptor为'red'的行的val值,其余置空 merged_df['val'] = merged_df.apply(lambda row: row['val'] if row['descriptor'] == 'red' else None, axis=1) print(merged_df)
方案2:向量化操作(更高效,适合大数据集)
import pandas as pd # 构造原始DataFrame df1 = pd.DataFrame({ 'date': ['jan', 'feb', 'mar', 'apr', 'may', 'jun'], 'product': ['product1', 'product2', 'product1', 'product2', 'product1', 'product2'], 'descriptor': ['blue', 'green', 'red', 'blue', 'red', 'red'] }) df2 = pd.DataFrame({ 'date': ['mar', 'may', 'jun'], 'product': ['product1', 'product1', 'product2'], 'val': ['x', 'y', 'z'] }) # 左连接获取val列 merged_df = df1.merge(df2, on=['date', 'product'], how='left') # 对非'red'的行清空val值 merged_df.loc[merged_df['descriptor'] != 'red', 'val'] = None print(merged_df)
内容的提问来源于stack exchange,提问作者katehasnoidea
相关产品推荐
相关产品推荐

