【发布时间】: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