如何用pandas的groupby().transform()获取特定行值而非函数计算结果?
Got it, let's solve this problem exactly how you need it. You want to pull the VISA price for each shop (even when it's not the minimum) so you can compare other payment methods against it—here are a couple of straightforward ways to do this with pandas:
First, let's set up your DataFrame
import pandas as pd data = { "Shop": ["Butcher", "Butcher", "Baker", "Baker", "Candlestick maker", "Candlestick maker"], "Item": ["A", "A", "B", "B", "C", "C"], "Card": ["AMEX", "VISA", "AMEX", "VISA", "AMEX", "VISA"], "Price": [1.5, 0.9, 2.5, 3.5, 1.5, 1.5] } df1 = pd.DataFrame(data)
Method 1: Using groupby + transform (matches your original workflow)
If you want to stick with transform like you were using for min prices, you can use a lambda function inside transform to grab the VISA price for each shop group:
# Add a column with the VISA price for each shop df1['VISA_Price'] = df1.groupby('Shop')['Price'].transform( lambda group: group[df1.loc[group.index, 'Card'] == 'VISA'].iloc[0] ) # Calculate the difference between current price and VISA price for easy comparison df1['Price_VS_VISA'] = df1['Price'] - df1['VISA_Price']
How this works:
groupby('Shop')splits the DataFrame into groups per shop- For each group, the lambda filters rows where
Card == 'VISA'(using the group's index to reference the originalCardcolumn) - We grab the first (and only, since each shop has one VISA entry) price with
iloc[0] transformbroadcasts this value to every row in the shop group
Method 2: Using a mapping dictionary (more efficient for large datasets)
If you're working with a bigger dataset, this method is faster because it avoids per-group lambda operations:
# Create a dictionary mapping each shop to its VISA price visa_price_map = df1[df1['Card'] == 'VISA'].set_index('Shop')['Price'].to_dict() # Map this to the original DataFrame df1['VISA_Price'] = df1['Shop'].map(visa_price_map) # Again, calculate the comparison column df1['Price_VS_VISA'] = df1['Price'] - df1['VISA_Price']
End Result
Either method will give you this output, where you can clearly see how each payment method's price stacks up against VISA:
Shop Item Card Price VISA_Price Price_VS_VISA 0 Butcher A AMEX 1.5 0.9 0.6 1 Butcher A VISA 0.9 0.9 0.0 2 Baker B AMEX 2.5 3.5 -1.0 3 Baker B VISA 3.5 3.5 0.0 4 Candlestick maker C AMEX 1.5 1.5 0.0 5 Candlestick maker C VISA 1.5 1.5 0.0
Now you can easily spot, for example, that AMEX is more expensive than VISA at the Butcher, but cheaper at the Baker!
内容的提问来源于stack exchange,提问作者sudonym

