簡體   English   中英

比較三列並選擇最高的

[英]Compare three columns and choose the highest

我有一個如下圖所示的數據集,

樣本數據

我的目標是比較最后三行並每次選擇最高的。

我有四個新變量:empty = 0、cancel = 0、release = 0、undertermined = 0

對於索引 0,cancelCount 是最高的,因此 cancel += 1。只有當三行相同時,未確定的才會增加。

這是我失敗的代碼示例:

    empty = 0 
    cancel = 0
    release = 0
    undetermined = 0
    if (df["emptyCount"] > df["cancelcount"]) & (df["emptyCount"] > df["releaseCount"]):
       empty += 1
   elif (df["cancelcount"] > df["emptyCount"]) & (df["cancelcount"] > df["releaseCount"]):
       cancel += 1
   elif (df["releasecount"] > df["emptyCount"]) & (df["releasecount"] > df["emptyCount"]):
       release += 1
   else:
       undetermined += 1

    ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

一般來說,您應該避免循環。 這是一個滿足您需要的矢量化代碼示例:

# data of intereset
s = df[['emptyCount', 'cancelCount', 'releaseCount']]

# maximum by rows
max_vals = s.max(1)

# those are equal to max values:
equal_max = df.eq(max_vals, axis='rows').astype(int)

# If there are single maximum along the rows:
single_max = equal_max.sum(1)==1

# The values:
equal_max.mul(single_max, axis='rows').sum()

Output 將是一個如下所示的系列:

emmptyCount    count1
cancelCount    count2
releaseCount   count3
dtype: int64

首先我們找到未確定的行

equal = (df['emptyCount'] == df['cancelcount']) | (df['cancelount'] == df['releaseCount'])

然后我們找到確定行的最大列

max_arg = df.loc[~equal, ['emptyCount', 'cancelcount', 'releaseCount']].idxmax(axis=1)

數一數

undetermined = equal.sum()
empty = (max_arg == 'emptyCount').sum()
cancel = (max_arg == 'cancelcount').sum()
release = (max_arg == 'releaseCount').sum()
import pandas as pd
import numpy as np


class thing(object):
    def __init__(self):
        self.value = 0

empty , cancel ,  release , undetermined = [thing() for i in range(4)]

dictt = {   0 : empty, 1 : cancel , 2 : release , 3 : undetermined   }

df = pd.DataFrame({
    'emptyCount': [2,4,5,7,3],
    'cancelCount': [3,7,8,11,2],
    'releaseCount': [2,0,0,5,3],   
})

for i in range(1,4):
    series = df.iloc[-4+i]
    for j in range(len(series)):
        if series[j] == series.max():
            dictt[j].value +=1

cancel.value

獲取最大值的小腳本:

import numpy as np

emptyCount = [2,4,5,7,3]
cancelCount = [3,7,8,11,2]
releaseCount = [2,0,0,5,3]

# Here we use np.where to count instances where there is more than one index with the max value. 
# np.where returns a tuple, so we flatten it using "for n in m"
count = [n for z in zip(emptyCount, cancelCount, releaseCount) for m in np.where(np.array(z) == max(z)) for n in m]

empty = count.count(0) # 1
cancel = count.count(1) # 4
release = count.count(2) # 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM