【问题标题】:Slicing of List contain datafram and strings列表切片包含数据框和字符串
【发布时间】:2021-12-29 09:25:17
【问题描述】:
R_1 = {
    'market': 'Boston',
    'summary': pd.DataFrame({
        "year": [2022, 2023],
        "customers": [400, 230],
        "count": [180, 1150]}),
    }
}

R_2 = {
    'market': 'New York',
    'summary': pd.DataFrame({
        "year": [2022, 2023],
        "customers": [410, 220],
        "count": np.array([185, 115])}),

    }
}

然后我使用了一个函数来附加这些结果

    def get_results_max(self, market: str, metric: str, year: int) -> dict

        """
    I need help to write this function
        """

然后调用下面全部追加,结果文件很多

get_max(market= 'New York', metric= "count", year: 2022)

我需要具有 2022 年纽约最大 box_count 值的 dict 以及其他值

【问题讨论】:

  • 在函数中,遍历你的结果字典的所有项目,检查市场是否相同,然后找到最大值。不确定 box_count 的用途
  • box_count 在结果中在summary_yearly 之下,如何使用year 对其进行切片,我们检查它是否相等,那么我们需要box_count 的最大值
  • 哦,所以你想从那个数组中找到最大值?好的,似乎有什么问题?
  • 从所有结果中,我需要 box_count 变量在 2022 年和纽约的最大值,注意:我有更多的 RESULT 文件和更多的纽约数据,我刚刚添加了 2
  • 是的,但有什么问题?循环遍历所有结果,检查结果是否包含您想要的数据(年份、市场)并保持最高值存储。

标签: python python-3.x pandas list slice


【解决方案1】:

你可以试试:

    ...

    def get_results_max(self, market, metric, year):
        metrics = [
            result["summary_yearly"].loc[
                result["summary_yearly"].year.eq(year), metric
            ].max()
            for result in self.results if result["market"] == market
        ]
        if metrics:
            return max(metrics)
        print(f"No result for market '{market}', metric '{metric}' and year '{year}'")

结果

sensi = Sensi()
sensi.add_result(RESULT_1)
sensi.add_result(RESULT_2)
print(sensi.get_results_max(market= 'New York', metric= "box_count", year=2022))

A new result for Boston has been added.
A new result for New York has been added.
188.70000000000002

【讨论】:

    猜你喜欢
    • 2016-10-27
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    • 2022-12-11
    • 1970-01-01
    • 2021-01-11
    • 2019-09-21
    相关资源
    最近更新 更多