如何使用另一pandas.DataFrame数据填充目标DataFrame列?
Solution Using Pandas Merge
To get your desired result, you'll use pandas' merge() function to join the two DataFrames based on matching values between second_key (from the first DataFrame) and key (from the second DataFrame). Here's a straightforward implementation:
Step 1: Set Up Your DataFrames
First, let's recreate the DataFrames you provided:
import pandas as pd # First DataFrame first_df = pd.DataFrame({ 'first_key': [0, 0, 0, 0, 0], 'second_key': [1, 1, 2, 3, 3] }) # Second DataFrame second_df = pd.DataFrame({ 'key': [1, 2, 3], 'status': ['good', 'bad', 'good'] })
Step 2: Merge and Clean Up
Use pd.merge() to combine the DataFrames, then remove the redundant key column that comes along with the merge:
merged_df = pd.merge( first_df, second_df, left_on='second_key', right_on='key', how='left' # Keeps all rows from the first DataFrame ).drop('key', axis=1)
Step 3: Check the Result
Printing merged_df will give you exactly the output you want:
first_key second_key status 0 0 1 good 1 0 1 good 2 0 2 bad 3 0 3 good 4 0 3 good
Quick Explanation
left_on='second_key'andright_on='key': Tells pandas to match rows where the value insecond_key(from the left DataFrame) equals the value inkey(from the right DataFrame).how='left': Ensures every row from your original first DataFrame is preserved, even if there's no matching entry in the second DataFrame (in such cases,statuswould showNaN)..drop('key', axis=1): Removes the duplicatekeycolumn added during the merge, leaving only the columns you need.
内容的提问来源于stack exchange,提问作者Sergey Malashenko
相关产品推荐
相关产品推荐

