【问题标题】:Is there a way to print previous date-time value in a dataframe for a condition?有没有办法在数据框中打印先前的日期时间值以获取条件?
【发布时间】:2019-11-11 20:37:14
【问题描述】:

我有一个数据集,其中包含数据时间和值作为每个 ID 的列。我对其进行了一些计算,但在使用递归函数时卡住了。

数据集如下所示,

Date-Time     Volume      ID    Load  
10/22/2019     3862       10        
10/23/2019     3800       10        
10/24/2019     3700       10        
10/25/2019     5000       10     Yes   
10/26/2019     4900       10        
10/27/2019     4800       10        
10/22/2019     3862       11        
10/23/2019     3800       11        
10/24/2019     3700       11        
10/25/2019     5000       11     Yes        
10/26/2019     4900       11        
10/27/2019     4800       11           

load_date 我需要的输出是,

Date-Time  Volume  ID  Load    LoadDate
10/22/2019    3862  10            0
10/23/2019    3800  10            0
10/24/2019    3700  10            0
10/25/2019    5000  10   Yes   10/25/2019
10/26/2019    4900  10         10/25/2019
10/27/2019    4800  10         10/25/2019
10/22/2019    3862  11            0
10/23/2019    3800  11            0
10/24/2019    3700  11            0
10/25/2019    5000  11   Yes   10/25/2019
10/26/2019    4900  11         10/25/2019
10/27/2019    4800  11         10/25/2019

【问题讨论】:

  • 您能否阐明您如何知道哪些行需要填充LoadDate 的逻辑?是因为他们的Load 等于Yes?还是基于当前日期?
  • @Kyle 是的,LoadDate 在Load = Yes 时给出。当Load = Yes 时,它将拥有present date,直到找到新的Load = Yes。这需要对每个ID

标签: python pandas dataframe datetime recursion


【解决方案1】:

IIUC,

我们可以在 Yes 值处建立索引,并通过一些索引过滤和.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

【讨论】:

  • @Amogh 那是因为你用 0 填充了空格,所以你不会得到正确的日期时间列,你应该改用fillna(pd.nat)
猜你喜欢
  • 2013-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多