Python中DataFrame特定行筛选、字段转换与结果拼接的技术方案问询
Great job getting the filtering logic working! Let's walk through the remaining steps to achieve your desired result.
Step 1: Transform the country field in the filtered subset
Once you have your filtered DataFrame df1, you can replace the "ca" value in the country column using pandas' replace() method—it's straightforward for single-value substitutions:
# Replace 'ca' with 'tx' in the country column of df1 df1['country'] = df1['country'].replace('ca', 'tx')
If you ever need to handle multiple replacements later (e.g., replace "ny" with another value), you can pass a dictionary to replace() for scalability:
df1['country'] = df1['country'].replace({'ca': 'tx', 'ny': 'custom_value'})
Step 2: Extract remaining rows from the original DataFrame
Next, we need to grab the rows that weren't included in your filtered subset. You can do this by negating the isin() check:
# Get rows where type is NOT in the selected values df2 = df[~df['type'].isin(vals)] # Alternatively, use query() to match your initial filtering style: # df2 = df.query('not type.isin(@vals)')
Step 3: Concatenate the transformed subset and remaining rows
Finally, use pd.concat() to combine the two DataFrames. Adding ignore_index=True ensures the final result has a clean, sequential index (you can omit this if you want to retain original row indices):
import pandas as pd # Combine the transformed subset and remaining rows final_df = pd.concat([df1, df2], ignore_index=True)
Full Working Code
Putting it all together, here's the complete script that matches your requirements:
import pandas as pd # Sample original DataFrame data = { 'id': [1, 2, 3], 'type': ['aa1', 'bb2', 'cc3'], 'stat': ['y', 'n', 'y'], 'country': ['ca', 'ny', 'tx'] } df = pd.DataFrame(data) # Your existing filtering logic out = input("select type value: ") vals = [v.strip() for v in out.split(',')] df1 = df.query('type.isin(@vals)') # Step 1: Transform country field df1['country'] = df1['country'].replace('ca', 'tx') # Step 2: Get remaining rows df2 = df[~df['type'].isin(vals)] # Step 3: Concatenate to get final result final_df = pd.concat([df1, df2], ignore_index=True) print(final_df)
Running this with input aa1, bb2 will output exactly the final DataFrame you provided.
内容的提问来源于stack exchange,提问作者Lynn

