簡體   English   中英

以pythonic方式重構代碼,得到最流行的元素 pandas dataframe

[英]Refactor code in a pythonic way to get the most popular elements in pandas dataframe

這是 dataframe:

圖像文件 對象
0 image_1.png [汽車,汽車,汽車,汽車,汽車,汽車,汽車,公共汽車,汽車]
1個 image_2.png [紅綠燈、車、車、車、車、車、車、車、車、車]
2個 image_3.png [車、紅綠燈、人、車、車、車、車]
3個 image_4.png [人,人,車,車,自行車,車,車]
4個 image_5.png [車、車、車、車、車、人、車、車、車]

objects 列是一個列表,其中包含圖像中 object 的頻率。

如果圖像中恰好有 3 個或更少的元素,我可以使用此代碼獲得最頻繁的元素:

result = []

# Iterate through rows of the dataframe
for i, row in df.iterrows():
    # Count the frequency of each object in the image
    frequencies = Counter(row['objects'])
    # Sort the frequencies from most to least common
    sorted_frequencies = sorted(frequencies.items(),
                                    key=lambda x: x[1],
                                    reverse=True
                                    )

    # Check if there are less than 3 different objects in the image
    if len(sorted_frequencies) <= 3:
        # If so, append all of the objects to the result list
        result.extend([obj for obj, _ in sorted_frequencies])

frequency_3_most_pop = dict(Counter(result))

我擔心的是 iterrows 不是對 dataframe 執行迭代的最佳選擇,我想重構代碼以避免它。 任何幫助,將不勝感激。

假設您在df['objects']中有列表,您可以簡化代碼:

frequency_3_most_pop = dict(Counter(x for l in df['objects']
                                    if len(c:=Counter(l))<=3 for x in c))

注意。 由於海象 ( := ) 運算符 ( PEP0572 ),需要 python 3.8+。

Output:

{'car': 5, 'bus': 1, 'traffic light': 2, 'person': 3, 'bicycle': 1}

定時

在 6k 行上執行

# original approach
346 ms ± 49.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# Counter generator (this approach)
11.5 ms ± 1.01 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

使用的輸入:

df = pd.DataFrame({'image_file': ['image_1.png', 'image_2.png', 'image_3.png', 'image_4.png', 'image_5.png'],
                   'objects': [['car', 'car', 'car', 'car', 'car', 'car', 'car', 'bus', 'car'],
                               ['traffic light', 'car', 'car', 'car', 'car', 'car', 'car', 'car', 'car', 'car'],
                               ['car', 'traffic light', 'person', 'car', 'car', 'car', 'car'],
                               ['person', 'person', 'car', 'car', 'bicycle', 'car', 'car'],
                               ['car', 'car', 'car', 'car', 'car', 'person', 'car', 'car', 'car']],
                  })

暫無
暫無

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

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