如何在 pandas 中使用 if 函数

How to use if function in pandas

我有一个数据框

我想在此数据框中添加一列作为 'VAR',如果 'END' 和 'START' 之间存在差异,则此新列中的值应更新为 "L" ]列大于等于365,否则应该是"S"

最终输出应该是

我知道这个答案不在 Pandas 中,但是标签 Excel 表明您也在使用 to_excel,所以:您可以简单地使用Excel的函数。假设第一个 "End" 值在 C4 列,"Start" 值是 B4,运行 这个函数:=IF(C4-B4>=365,"L","S") 你会得到想要的结果。如果您想单独在 Pandas 中执行此操作,请查看 答案,您可以为该列添加一个 if 检查。

读取 pandas 数据框中的数据后,将 StartEnd 列转换为 pandas.to_datetime:

df1 = pd.DataFrame({'Start':['21-01-2015','28-02-2019','07-04-2017','01-01-2019'],
                   'End':['25-11-2021','02-01-2020','10-02-2020','31-12-2019']})

df1['Start'] = pd.to_datetime(df1['Start'])
df1['End'] = pd.to_datetime(df1['End'])

#Take difference between 'End' and 'Start'

df1['diff'] = (df1['End'] - df1['Start']).dt.days

#Then use lambda function to apply the condition:

df1['Var'] = df1['diff'].apply(lambda x: 'L' if x > 364 else 'S')

print(df1)

       Start        End  diff Var
0 2015-01-21 2021-11-25  2500   L
1 2019-02-28 2020-02-01   338   S
2 2017-07-04 2020-10-02  1186   L
3 2019-01-01 2019-12-31   364   S

#Then drop the temporary diff column

df1 = df1.drop(['diff'], axis = 1)