[英]Operations on existing Excel sheet using Pandas
I have two csv files and I have merged the csv files and exported them to an Excel sheet. 我有两个csv文件,我已合并csv文件并将它们导出到Excel工作表。
Now can I add a new column in the existing Excel sheet where the result of the new column will be division operation of two columns existing. 现在我可以在现有的Excel工作表中添加一个新列,其中新列的结果将是现有两列的除法运算。
Example: 例:
col_new=col4/col6
I have tried to implement with csv files where after merging the files the final csv file would be like this: 我试图用csv文件实现,在合并文件之后,最终的csv文件将是这样的:
col1,col2,col3
"1,200",14,2
"1,600",13,4
data=pd.read_csv(filename)
for i,l in zip(data['col1'],data['col3']):
sah=i.replace(',','')
sah1=int(float(sah))
print sah1
print type(sah1)
data['res']=sah1/l
print data
Expected: 预期:
col1 col2 col3 res
---------------------------
1,200 14 2 600
1,600 13 4 400
You can convert the first column to an integer using str.replace(',','')
as you have done and then use pd.to_numeric()
to recast the entire series at once. 您可以使用str.replace(',','')
将第一列转换为整数,然后使用pd.to_numeric()
一次重铸整个系列。 Now that you have the two columns you're interested in as integers, just use the ability to divide one series by another and store that in res
. 现在你有两个你感兴趣的列作为整数,只需使用将一个系列除以另一个系列的能力并将其存储在res
。 From there, you can export it to a csv or excel file. 从那里,您可以将其导出到csv或excel文件。
# set up the DataFrame to match your input
df = pd.DataFrame([["1,200", 14, 2],["1,600", 13, 4]], columns=['col1','col2','col3'])
print(df)
# col1 col2 col3
# 0 1,200 14 2
# 1 1,600 13 4
df['res'] = pd.to_numeric(df.col1.str.replace(',','')) / df.col3
print(df)
# col1 col2 col3 res
# 0 1,200 14 2 600.0
# 1 1,600 13 4 400.0
Part of the issue I see in your code is data['res']=sah1/l
is saying data['res']
is a scalar. 我在你的代码中看到的部分问题是data['res']=sah1/l
表示data['res']
是一个标量。 So it will fill the entire column with that singular value rather than evaluating row wise. 因此,它将使用该奇异值填充整个列,而不是逐行评估。 It will do this each iteration which is why you see the res
column the same every time it prints. 它会在每次迭代时执行此操作,这就是为什么每次打印时都会看到res
列相同的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.