英文:
Using an for to repeat the number o rows in pandas
问题
Sure, here's the translated code portion:
嗨,我尝试使用一个 for 循环来重复行数。
valorrepetir = []
for index, row in tabela.iterrows():
print(int(row['Quantidade Entrada']))
valorrepetir.append(int(row['Quantidade Entrada']))
for i in valorrepetir:
print(i)
tabela_new = pd.DataFrame(np.repeat(tabela.values, i, axis=0))
I hope this helps!
英文:
Hy. im trying to use an for to repeat the number of rows.
valorrepetir = []
for index, row in tabela.iterrows():
print(int(row['Quantidade Entrada']))
valorrepetir.append(int(row['Quantidade Entrada']))
for i in valorrepetir:
print(i)
tabela_new = pd.DataFrame(np.repeat(tabela.values, i, axis=0))
I use this code but instead of replicating the lines based on a value that is stock in each line it repeats all the lines based on the last stock number of the last line
I think the problem is in the second for when a create a new dataframe but i dont know how to do it.
Can anyone help?!!
答案1
得分: 1
You should create the new data frame outside the loop that iterates over valorrepetir, and then use the repeat() function to repeat each row of the original data frame based on the value in valorrepetir.
你应该在迭代`valorrepetir`的循环之外创建新的数据框,然后使用repeat()函数根据`valorrepetir`中的值重复原始数据框的每一行。
tabela = pd.DataFrame({'Quantidade Entrada': [2, 3, 4], 'Valor': [10, 20, 30]})
valorrepetir = tabela['Quantidade Entrada'].tolist()
tabela_new = tabela.loc[np.repeat(tabela.index.values, valorrepetir)]
print(tabela_new)
英文:
You should create the new data frame outside the loop that iterates over valorrepetir, and then use the repeat() function to repeat each row of the original data frame based on the value in valorrepetir.
tabela = pd.DataFrame({'Quantidade Entrada': [2, 3, 4], 'Valor': [10, 20, 30]})
valorrepetir = tabela['Quantidade Entrada'].tolist()
tabela_new = tabela.loc[np.repeat(tabela.index.values, valorrepetir)]
print(tabela_new)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论