如何在Pandas中填写多个布尔条件

2024-10-03 11:21:36 发布

您现在位置:Python中文网/ 问答频道 /正文

I found an alternate answer herelink

我的数据帧当前看起来像这样

          date  new_cases   new_deaths  new_tests   year    month   day weekday
0   2019-12-31  0.0                 0.0       NaN   2019    12      31   1
1   2020-01-01  0.0                 0.0       NaN   2020    1        1   2
2   2020-01-02  0.0                 0.0       NaN   2020    1        2   3

我想通过一个代码来平均出工作日和周末的“新案例” 我的代码目前看起来像这样,但我只能通过1个条件,即'==6'。我想通过多个条件,例如,==(4,5,6)

covid_df[covid_df.weekday == 6].new_cases.mean()

有线索吗


Tags: 数据代码answerandfnewdatenan
2条回答

您可以将groupby()日期设置为工作日或周末。下面的代码源代码并演示了这一点

import requests
import io
import pandas as pd

dfall = pd.read_csv(io.StringIO(requests.get(
    "https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv").text))
dfall["date"] = pd.to_datetime(dfall["date"])

dtlcols = ["date", "iso_code", "location", "continent"]
cols = ["new_cases", "new_deaths", "new_tests"]
dfall.loc[dfall["iso_code"].eq("GBR"), dtlcols + cols].groupby(
    dfall["date"].dt.dayofweek.isin([5, 6]), as_index=False
).agg({**{c: "last" for c in dtlcols}, **{c: "mean" for c in cols}})
^{tb1}$

我想你在找isin

# you can use `loc` to access `new_cases` also
days = [4, 5, 6]
df.loc[df.weekday.isin(days), "new_cases"].mean()

选择weekdaydays列表中的行;然后选择new_cases

相关问题 更多 >