Python 是否有方法在数据框中打印某个条件的上一个日期时间值?
我有一个数据集,它的数据时间和值作为每个ID的列。我对它进行了一些计算,但在使用递归函数时卡住了 数据集如下所示 load_date需要的输出是 IIUC 我们可以按“是”值编制索引,并使用一些索引筛选和Python 是否有方法在数据框中打印某个条件的上一个日期时间值?,python,pandas,dataframe,datetime,recursion,Python,Pandas,Dataframe,Datetime,Recursion,我有一个数据集,它的数据时间和值作为每个ID的列。我对它进行了一些计算,但在使用递归函数时卡住了 数据集如下所示 load_date需要的输出是 IIUC 我们可以按“是”值编制索引,并使用一些索引筛选和.loc辅助功能向前填充任何日期 idx = df.loc[df['Load'] == 'Yes'].index # get all index values for Yes. df['LoadDate'] = np.nan # create your col. df.loc[idx, 'Lo
.loc
辅助功能向前填充任何日期
idx = df.loc[df['Load'] == 'Yes'].index # get all index values for Yes.
df['LoadDate'] = np.nan # create your col.
df.loc[idx, 'LoadDate'] = df['Date-Time']
Groupby并创建您的
df['LoadDate'] = (df.groupby('ID')['LoadDate'].ffill()).fillna(0)
#group by ID and ffill the load date and fill and nan's as 0.
这就给我们留下了很多问题。
print(df)
Date-Time Volume ID Load LoadDate
0 10/22/2019 3862 10 0
1 10/23/2019 3800 10 0
2 10/24/2019 3700 10 0
3 10/25/2019 5000 10 Yes 10/25/2019
4 10/26/2019 4900 10 10/25/2019
5 10/27/2019 4800 10 10/25/2019
6 10/22/2019 3862 11 0
7 10/23/2019 3800 11 0
8 10/24/2019 3700 11 0
9 10/25/2019 5000 11 Yes 10/25/2019
10 10/26/2019 4900 11 10/25/2019
11 10/27/2019 4800 11 10/25/2019
请澄清您如何知道哪些行需要
LoadDate
填充的逻辑?是不是因为他们的负载
等于是
?还是基于当前日期?@Kyle Yes,加载日期是在Load=Yes
时给出的。当Load=Yes
时,它将具有当前日期
,直到找到新的Load=Yes
。这需要对每一个<代码> ID>代码> @ AMOGH进行,这是因为你用0填充空格,所以你不能得到一个适当的DATION列,你应该使用<代码> fILNA(P.NAT)< /C>。
df['LoadDate'] = (df.groupby('ID')['LoadDate'].ffill()).fillna(0)
#group by ID and ffill the load date and fill and nan's as 0.
print(df)
Date-Time Volume ID Load LoadDate
0 10/22/2019 3862 10 0
1 10/23/2019 3800 10 0
2 10/24/2019 3700 10 0
3 10/25/2019 5000 10 Yes 10/25/2019
4 10/26/2019 4900 10 10/25/2019
5 10/27/2019 4800 10 10/25/2019
6 10/22/2019 3862 11 0
7 10/23/2019 3800 11 0
8 10/24/2019 3700 11 0
9 10/25/2019 5000 11 Yes 10/25/2019
10 10/26/2019 4900 11 10/25/2019
11 10/27/2019 4800 11 10/25/2019