Это не самое тонкое решение, но я думаю, оно делает более очевидным, что происходит. Я уверен, что это может быть сокращено до более краткого кода.
import pandas as pd
# Generating a similar df
df = pd.DataFrame({'Order' :[1,2,3,4,5,6,7],
'Price' :[27850.00,27850.00,27860.85,27860.85,27860.85,27979.00,27979.00],
'Quantity':[2040, 1980, 1800, 2340 ,1500, 1840, 2020 ]
})
print(df)
print("--------------")
# Get the unique values from the Price column
# This tells us which values we want to select the highest value from
values = df["Price"].unique()
# Loop through the values, selecting the rows which match each value, one at a time
for value in values:
# df["Price"] == value" (Selects all the rows where price equals ONE of the values)
# For example, the above will give us 3 rows where Price == 27860.85
# .max() gives us the row with the largest value from Quantity, since the Price column are all equal
# The above would give us a Series with two values, Price and Quantity. I.e.
# Price 27860.85
# Quantity 2340.00
# ["Quantity"] then selects only the Quantity value and assigns it to highest
highest = df[df["Price"] == value].max()["Quantity"]
print(value, "...", highest)
# You can, during this loop, build a new dict object to create a new df if desired
Или, более кратко ...
# Create a new list in one line
highest = [ df[df["Price"] == value].max()["Quantity"] for value in df["Price"].unique()]
# Add as columns to new df
df1 = pd.DataFrame({
'Price' :df["Price"].unique(),
'Quantity':highest
})
print(df1)
Используйте ту же идею, чтобы получить соответствующее значение из других столбцов для каждого уникального Price
и добавить их в новыйdf1