python - 根据另一个引用追加

标签 python numpy

我可以使用 Numpy 来完成任务。

我需要用两个列表显示一个月内的总销售额:日期和销售额。

我的方法是通过删除日期中的月份、创建二维矩阵并添加检查每个月的值来制作一个月内所有销售的列表。

import numpy as np

dates = ["02/01/19", "03/02/19"]
sales = ["10.50", "12.20"]
month = [x.strip("0").split("/")[0] for x in dates]
monthsales = np.vstack((month, sales)).astype(np.float)

def monthlysales():
    jan = []
    for i in monthsales[0, 0:]:
        if i == 1:
            jan.append()
    s = input("Pick month: ")
    if s == "1":
        print("Sales total for Jan is:", np.sum(jan), "USD")
    else:
        print("Not a valid month")
    return
print(monthsales)
print(monthlysales())

问题是我不知道要附加什么,因此它需要矩阵的第二行,这将完成代码

最佳答案

保持逻辑的解决方案:

在这里,我循环月份(就像您所做的那样,但这里使用 enumerate),并查找月份何时等于 1。使用 enumerate 允许我们知道月份等于 1 时的列号 (id)。然后只需在我们感兴趣的月份 (id) 附加销售额(第 1 行)

import numpy as np

dates = ["02/01/19", "03/02/19"]
sales = ["10.50", "12.20"]
month = [x.strip("0").split("/")[0] for x in dates]
monthsales = np.vstack((month, sales)).astype(np.float)

def monthlysales():
    jan = []
    # Loop over months with enumerate
    for id, month in enumerate(monthsales[0]):
        if month == 1:
            # Append sales (row 1) at column id
            jan.append(monthsales[1, id])
    s = input("Pick month: ")
    if s == "1":
        print("Sales total for Jan is:", np.sum(jan), "USD")
    else:
        print("Not a valid month")

print(monthsales)
print(monthlysales())

当然,既然你可以使用 numpy,你就可以完全避免任何循环。考虑以下行:

monthsales[1, monthsales[0] == 1].sum()

这将一月所有月份的销售额汇总在一行中。没有循环。对于任何合理数量的数据,这将比使用 enumerate 的解决方案快得多。

看起来更像是您最初的解决方案:

def monthlysales():
    s = int(input("Pick month: "))
    if s >= 1 and s <= 12:
        monies = monthsales[1, monthsales[0] == s].sum()
        print("Sales total for month {} is {} USD".format(s, monies))
    else:
        print("Not a valid month")

关于python - 根据另一个引用追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56823355/

相关文章:

python - 从子类中引用非重写父类(super class)方法的约定是什么?

python - 从第一个标签中获取一个简单的字符串

python - 对列表 pandas 的列表进行过滤

python - Django REST 序列化单个模型实例

Python numpy 数组切片不是 Fortran 连续的

python - 使用 LabelEncoder 转换数据

python - Holoviews 曲线中的关键维度用于在字典中查找值

python - 在 python 中,获取 2d numpy 数组中值总和的最有效方法是什么?

python - "Defaulting to user installation because normal site-packages is not writeable" python 消息

python - 将一列与包含分类值的多列进行比较,无需循环