英文:
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
答案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
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)
英文:
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
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论