循环用于创建多个列表

huangapple go评论69阅读模式
英文:

Loop for creating multiple list

问题

我无法找到一种方法来创建一个循环,提取数据框的第一行中处于前20百分位的值,并将相关的列标题存储在一个名为"top_2017"的列表中。对于每一行都应该执行这个操作,但我无法使"等式的左侧"变得动态。

我尝试了不同的循环和使用了"i",但是一旦我将它写在等式的左侧,它被识别为一个简单的字母。

英文:

I can't find a way to create a loop that extracts the values in the top 20 percentile of a data frame's first row and stores the associated column header in a list name, for example, "top_2017".

it should do this for every row and create a different list per row, but I cannot make the "left part of the equal" dynamic.

I tried different loops with "i" but, once I write it in the left part of the equation, it is recognised as a simple letter

enter image description here

答案1

得分: 0

Preparing the data:

import pandas as pd
from random import sample
data = [sample(range(i * 100, (i + 1) * 100), 100) for i in range(10)]

df = pd.DataFrame(data)
df

first output: the DataFrame
循环用于创建多个列表

matriz = []
for _, ro in df.iterrows(): # row
    lista = list(enumerate(ro)) # position, value
    matriz.append(sorted(lista, key = lambda x: x[1], reverse = True)) # # top in beginning positions

top20 = len(matriz[0]) // 5 # top 20% each row
lista, lista20 = [], [] # prepare results
for ro in matriz: # row
    for p, v in ro[:top20]: # position, value
        lista.append(p) # sure of bigger values, get its position
    lista20.append(lista) # ready the row, you may append it
    lista = [] # reinitializes the row
print(lista20)

The output:
循环用于创建多个列表

英文:

Preparing the data:

import pandas as pd
from random import sample
data = [sample(range(i * 100, (i + 1) * 100), 100) for i in range(10)]

df = pd.DataFrame(data)
df

first output: the DataFrame
循环用于创建多个列表

matriz = []
for _, ro in df.iterrows(): # row
    lista = list(enumerate(ro)) # position, value
    matriz.append(sorted(lista, key = lambda x: x[1], reverse = True)) # # top in beginning positions

top20 = len(matriz[0]) // 5 # top 20% each row
lista, lista20 = [], [] # prepare results
for ro in matriz: # row
    for p, v in ro[:top20]: # position, value
        lista.append(p) # sure of bigger values, get its position
    lista20.append(lista) # ready the row, you may append it
    lista = [] # reinitializes the row
print(lista20)

The output:
循环用于创建多个列表

huangapple
  • 本文由 发表于 2023年3月7日 06:24:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75656393.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定