Pandas idxmin axis1 返回错误的列名值

2024-04-27 20:43:35 发布

您现在位置:Python中文网/ 问答频道 /正文

熊猫的价值:

Index   Bra Obr Zal Uto Str Nah Tec Ryc Hla BestP_A BestP_Amin  BestP_minA
0       461 38  44  46  49  137 324 322 162 Bra     Obr         137.0
1       442 32  30  35  39  180 322 325 180 Bra     Obr         180.0
2       152 28  23  23  30  175 335 355 206 Bra     Obr         175.0
3       38  33  68  33  49  119 223 46  46  Zal     Obr         46.0
4       36  33  203 36  46  217 253 166 170 Zal     Obr         166.0
5       35  84  38  41  54  49  175 57  141 Obr     Nah         49.0
6       34  45  71  45  59  72  207 57  60  Zal     Obr         57.0

Value from Pandas

我需要返回列名到列“BestP\u Amin”,Python返回错误的列名。值索引0示例:

BestP_A = Bra, Bra = 461, Nah = 137, Tec = 324, Ryc = 322, Hla = 162

代码:

if data.at[i,'BestP_A'] == 'Bra':
    data['BestP_Amin'] = data[['Bra','Nah','Tec','Ryc','Hla']].idxmin(axis=1) 

返回值Obr,问题在哪里? 块代码:

# nalezení nejleší pozice, přepočet podle výše atributů
for i in range(0,len(data.index)):
# nalezení pozice
    data['BestP_A'] = data[['Bra','Obr','Zal','Uto']].idxmax(axis=1)
#nalezení nejmenšího atributu
# VRACI CHYBNE HODNOTY
    if data.at[i,'BestP_A'] == 'Bra':
         data['BestP_Amin'] = data[['Bra','Nah','Tec','Ryc','Hla']].idxmin(axis=1)
    elif data.at[i,'BestP_A'] == 'Obr':
         data['BestP_Amin'] = data[['Obr','Nah','Tec','Ryc','Hla']].idxmin(axis=1)
    elif data.at[i,'BestP_A'] == 'Zal':
         data['BestP_Amin'] = data[['Zal','Nah','Tec','Ryc','Hla']].idxmin(axis=1)
    elif data.at[i,'BestP_A'] == 'Uto':
         data['BestP_Amin'] = data[['Uto','Nah','Tec','Ryc','Hla']].idxmin(axis=1)

    data.at[i,'BestP_minA'] = min(data.at[i,'Nah'],data.at[i,'Tec'],data.at[i,'Ryc'],data.at[i,'Hla'])
    data.at[i,'BestA_U'] = int(round(data.at[i,'BestA']*(data.at[i,'Ene']/100)*(1+(.25*data.at[i,'Sou']/100)+(.2*data.at[i,'Zku']/100)),0))

Block code in python:


Tags: dataathlatecaxisbraidxminnah
3条回答

嗯,循环“For”必须用于“If”。需要“BestP\u A”中的测试值并更改填充“BestP\u Amin”的选项

解决,使用元组

for i in range(0,len(data.index)):
    ...
    ...
    if data.at[i,'BestP_A'] == 'Bra':
        polemin = [data.loc[i,'Bra'],data.loc[i,'Nah'],data.loc[i,'Tec'],data.loc[i,'Ryc'],data.loc[i,'Hla']]
        data.at[i,'BestP_Min'] = min(polemin)
        data.at[i,'BestP_Idx'] = polemin.index(min(polemin))
    elif data.at[i,'BestP_A'] == 'Obr':
        polemin = [data.loc[i,'Obr'],data.loc[i,'Nah']...

我不知道您为什么要使用for循环,但是如果您的目标是获取值最小的列之间的列名,那么仅此行就足够了:

df['BestP_Amin'] = df[['Bra','Nah','Tec','Ryc','Hla']].idxmin(axis=1)

无需将它放入带有这些if语句的for循环中。idxmin已经对每一行执行矢量化搜索,并生成结果列。
在此之后,列将显示为:

0    Nah
1    Nah
2    Bra
3    Bra
4    Bra
5    Bra
6    Bra

相关问题 更多 >