使用”for”来重复pandas中的行数。

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

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)

huangapple
  • 本文由 发表于 2023年4月17日 20:58:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76035414.html
匿名

发表评论

匿名网友

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

确定