繁体   English   中英

使用 Python 查找 excel 文件中两列数字之间的差异

[英]Using Python to find the difference between two columns of numbers from an excel file

我有一个 excel 文件,我使用 pandas 将其导入到 Python 中,它有两列,购买价格和销售价格。 它们都是数值。 我想使用 python 自动为我计算以找到两者之间的差异,在这种情况下,我希望它是销售价格减去购买价格。 是否可以为此编写脚本? 在此先感谢您的帮助。

# create new column named profit
df['profit'] = df['Sales Price'] - df['Purchase Price']

将熊猫导入为 pd

将 Excel 文件读入 pandas DataFrame

df = pd.read_excel('文件.xlsx')

找出两列之间的差异

df['差异'] = df['column1'] - df['column2']

打印生成的 DataFrame

打印(df)

当然,您将需要迭代您拉入 pandas 的列,类似于下面的伪代码

import pandas as pd
file = "path/to/file.csv"
df = pd.read_csv(file)
mapped_sales_price = df['Sales Price'].values()
mapped_purchase_price = df['Purchase Price'].values()
profit = [x - y for x in mapped_sales_price for y in mapped_purchase_price]
print(profit) 

从这里您可以轻松地在 pandas 数据框中创建一个新列,其中包含利润以查看每行的利润,但是如果您只对您记录的整个 csv 条目的总利润感兴趣,那么您可以使用利润数组(列表)

total_profit = sum(int(i for i in profit))

这会将任何字符串转换为整数,如果你有浮点值那么你需要这样的东西

import math
normalized_profit_values = list(map( float, profit))
total_profit = math.fsum(normalized_profit_values)

    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM