基于其他列添加条件列:根据x、y值生成新列z
Hey there! Your requirement is essentially to create a column z that takes the minimum value between x and y — since when x > y you want z=y, otherwise z=x, that's exactly picking the smaller of the two values. Let's cover a few common ways to do this depending on what tool you're using:
1. Using Pandas (Python)
If you're working with data in Python, Pandas makes this super straightforward. Here's a complete example:
import pandas as pd # Set up your sample data df = pd.DataFrame({ 'x': [3, 5, 6, 1, 9], 'y': [4, 2, 6, 7, 4] }) # Create the z column by taking the minimum of x and y row-wise df['z'] = df[['x', 'y']].min(axis=1) # Print the result print(df)
Running this will output exactly what you need:
x y z 0 3 4 3 1 5 2 2 2 6 6 6 3 1 7 1 4 9 4 4
2. Using Excel/Google Sheets
For spreadsheet tools, it's even simpler. In the first cell of your z column (say, cell C2 if x is in column A and y in column B), enter the formula:=MIN(A2,B2)
Then just drag the fill handle down to apply it to all rows — that's it!
3. Using SQL
If you're working with a database table, you can use either a CASE statement (which works across all SQL dialects) or the LEAST function (supported in most major databases like MySQL, PostgreSQL):
Using CASE statement (universal):
SELECT x, y, CASE WHEN x > y THEN y ELSE x END AS z FROM your_table;
Using LEAST (shorter, if supported):
SELECT x, y, LEAST(x, y) AS z FROM your_table;
Whichever tool you pick, you'll end up with the desired result:
| x | y | z |
|---|---|---|
| 3 | 4 | 3 |
| 5 | 2 | 2 |
| 6 | 6 | 6 |
| 1 | 7 | 1 |
| 9 | 4 | 4 |
内容的提问来源于stack exchange,提问作者iGada

