[英]How to append the few datas into excel file using Python Pandas
[英]How to save multiple datas using pandas into excel
我正在尝试使用 pandas 将以下代码的输入和输出打印到 excel 表中。 如何使用 for 循环将多个数据值写入输出文件?
import random
import pandas as pd
def result(a,b):
return a+b
for i in range(10):
a = random.randint(1,100)
b = random.randint(1,100)
res = result(a,b)
col1 = 'num1'
col2 = 'num2'
col3 = 'result'
data = pd.DataFrame({col1:[a],col2:[b],col3:[res]})
data.to_excel('output.xlsx', sheet_name='sheet1', index=False)
当我运行上面的代码时,我只在 excel 表中得到最后的循环执行。 请给我一些建议。
预期输出:
如果您愿意使用不需要 for 循环的技术,这将为您提供所需的 2 列随机数据,1 到 100 之间,10 行
import pandas as pd
import numpy as np
#Random 2 columns of data between 1 and 100 with 10 rows
df = pd.DataFrame(np.random.randint(0,100,size=(10, 2)), columns=['Column1', 'Column2'])
#Sums column1 and 2 as result
df['Result'] = df['Column1'].add(df['Column2'])
#Saves to the excel file you specified
df.to_excel('output.xlsx', sheet_name='sheet1', index=False)
在您编写的循环中,您只是在每次迭代中为每一列更新一个值,并仅用单行(即在每次迭代中)再次编写整个 excel。
这里的逻辑是不对的。
以下代码是具有预期输出的相同代码的易于理解的版本: import random import pandas as pd def result(a,b): return a+b col1 = 'num1' col2 = 'num2' col3 = 'result' sample_dict = {col1: [], col2:[], col3:[]} for i in range(10): a = random.randint(1,100) b = random.randint(1,100) res = result(a,b) sample_dict[col1].append(a) sample_dict[col2].append(b) sample_dict[col3].append(res) output_df = pd.DataFrame(sample_dict) output_df.to_excel('output.xlsx', sheet_name='sheet1', index=False)
您的代码中有一个错误。 当您将数据写入 pandas 数据帧时,每次它都会被最后一个值覆盖,因此您将最后一个值作为输出,并且较早的值不会持续存在。 我的建议是将 3 个值保存到一个列表中,然后用这个列表列表创建一个数据框。 查看下面的代码:
import random
import pandas as pd
list_of_columns = []
def result(a,b):
return a+b
for i in range(10):
a = random.randint(1,100)
b = random.randint(1,100)
res = result(a,b)
list_of_columns.append([a,b,res])
data = pd.DataFrame(list_of_columns)
data.columns = ['num1', 'num2','result']
data.to_excel('output.xlsx', sheet_name='sheet1', index=False)
希望这可以帮助 !
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.