【问题标题】:Python - How add Column to DataFrame based on multple criteria from the same DataFramePython - 如何根据来自同一 DataFrame 的多个条件将 Column 添加到 DataFrame
【发布时间】:2023-03-11 21:50:02
【问题描述】:

我正在尝试在来自 CSV 文件的 DataFrame 中创建一个新列。有点棘手的是,这个新列的值取决于 DataFrame 中其他列的条件。

输出列取决于此数据框中以下列的值:VaccineCode | Occurrence | VaccineN | firstVaccineDate

因此,如果满足特定疫苗的条件,我必须将 ApplicationDate 列中的相应日期相加,以便告知第二剂的疫苗日期。

我的代码:

import pandas as pd
import datetime
from datetime import timedelta, date, datetime

df = pd.read_csv(path_csv, engine='python', sep=';')

criteria_Astrazeneca = (df.VaccineCode == 85) & (df.Occurrence == 1) & (df.VaccineN == 1)
criteria_Pfizer = (df.VaccineCode == 86) & (df.Occurrence == 1) & (df.VaccineN == 1)
criteria_CoronaVac = (df.VaccineCode == 87) & (df.Occurrence == 1) & (df.VaccineN == 1)

days_pfizer = 56
days_coronaVac = 28
days_astraZeneca = 84

到目前为止我已经尝试过:

df['New_Column'] = df[criteria_CoronaVac].firstVaccineDate + timedelta(days=days_coronaVac)

这一直有效,直到我必须完成与其他结果相同的New_Column,如下所示:

df['New_Column'] = df[criteria_CoronaVac].firstVaccineDate + timedelta(days=days_coronaVac)
df['New_Column'] = df[criteria_Pfizer].firstVaccineDate + timedelta(days=days_pfizer)
df['New_Column'] = df[criteria_AstraZeneca].firstVaccineDate + timedelta(days=days_astraZeneca)

当然,这种方法的问题在于下一条语句会覆盖之前的语句,所以我最终得到的只是New_Column 填充了上一条语句的结果。我需要一种将所有结果放在同一列中的方法。

我最后一次尝试是:

df['New_Column'] = df[criteria_CoronaVac].firstVaccineDate + timedelta(days=days_coronaVac)
df[criteria_Pfizer].loc[:,'New_Column'] = df[criteria_Pfizer].firstVaccineDate + timedelta(days=days_pfizer)

但它给出了以下错误:

A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
    self._setitem_single_column(ilocs[0], value, pi)

【问题讨论】:

标签: python python-3.x pandas dataframe


【解决方案1】:

您还可以使用数据框转换来创建新规则

【讨论】:

    【解决方案2】:

    非常感谢@ddejohn,第一个链接帮助我解决了我的问题,如下所示:

    df['New_Column'] = df[criteria_CoronaVac].firstVaccineDate + timedelta(days=days_coronaVac)
    df.loc[criteria_Pfizer,'New_Column'] = df[criteria_Pfizer].firstVaccineDate + timedelta(days=days_pfizer)
    df.loc[criteria_Astrazeneca,'New_Column'] = df[criteria_Astrazeneca].firstVaccineDate + timedelta(days=days_astraZeneca)
    

    这样,第一个语句创建列并填充 coronavac 索引,接下来的语句仅在相应索引中填充同一列。 问题已解决,再次感谢。

    【讨论】:

      猜你喜欢
      • 2018-09-10
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多