![](/img/trans.png)
[英]Pandas, Python : How to get the max value across columns while also satisfying a second condition
[英]Using Pandas, how can I find the min/max value and index from one set of columns, satisfying condition on a corresponding set of columns?
我有一個 DataFrame 有兩組具有匹配名稱的列(x1, x2, ... 和 y1, y2, ...)。
對於我的 DataFrame 中的每一行,我需要創建一個包含最小/最大 x 列的新列,以便分別最小化/最大化 y。
使用 Excel,我可以使用這種公式來接近所需的結果:
=MINIFS(<x-columns>,<y-columns>,MIN(<y-columns>))
=MAXIFS(<x-columns>,<y-columns>,MAX(<y-columns>))
雖然我還需要使用 Pandas 的idxmin
和idxmax
來獲取列名。
例如,以下數據行需要返回 55/x2(最小 xi,使得 yi = ymin)和 56/x3(最大 xi,使得 yi = ymax)
df = pd.DataFrame([[30, 55, 56, 73, 50, 3, 0, 3, 0, 3]], columns=['x1', 'x2', 'x3', 'x4', 'x5', 'y1', 'y2', 'y3', 'y4', 'y5'])
df['ymin'] = df.filter(regex='^y').min(axis=1)
df['ymax'] = df.filter(regex='^y').max(axis=1)
這是我的方法,經過多次試驗和錯誤:
new_df = (pd.wide_to_long(df.reset_index(),
stubnames=['x','y'],
i='index',
j='xy')
.reset_index()
.drop('xy', axis=1)
.groupby(['index', 'y'])['x'].agg(['max', 'min'])
.groupby('index')
.apply(lambda x: pd.Series(x.values[[0,-1], [1,0]],
index=['ymin', 'ymax']) )
)
輸出:
ymin ymax
index
0 55 56
更新:如果您還想要列名,這可以是一個選項:
new_df = (pd.wide_to_long(df.reset_index(),
stubnames=['x','y'],
i='index',
j='xy')
.reset_index()
)
u = (new_df.groupby(['index', 'y'])['x'].agg(['idxmax','idxmin'])
.groupby('index')
.apply(lambda x: pd.Series(x.values[[0,-1], [1,0]],
index=['ymin', 'ymax']) )
)
然后:
new_df.loc[u['ymin']]
給出:
index xy x y
1 0 2 55 0
和
new_df.loc[u['ymax']]
給出:
index xy x y
2 0 3 56 3
感謝 Quang Hoang,我設法將這個函數組合在一起,得到了我想要的結果:
def conditional_minmax(df, xprefix, yprefix):
new_df = (pd.wide_to_long(df.reset_index(),
stubnames=[xprefix, yprefix],
i='index',
j='xy')
.reset_index()
.drop('xy', axis=1)
.groupby(['index', yprefix])[xprefix].agg(['max', 'min'])
.groupby('index')
.apply(lambda x: pd.Series(x.values[[0, -1], [1, 0]],
index=['_xmin', '_xmax']))
)
new_df['_xidxmin'] = abs(df.filter(regex='^' + xprefix).sub(new_df['_xmin'], axis=0)).idxmin(axis=1)
new_df['_xidxmax'] = abs(df.filter(regex='^' + xprefix).sub(new_df['_xmax'], axis=0)).idxmin(axis=1)
return new_df
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.