根据条件在熊猫数据框行之间填充rmultiple流

时间:2019-09-08 11:07:11

标签: python pandas

我有一个数据框,其中有按日期分类的取款/贷项和期末余额信息。

date      withdraw     credit    closing_balance
02/06/17    2,500.00      nan           6,396.77
03/06/17      nan      36,767.00       43,163.77
05/06/17    1,770.00      nan          41,393.77
05/06/17     6000.00      nan           35393.77
05/06/17      278.00      nan           35115.77
07/06/17     1812.00      nan           33303.77

现在我们可以看到该表中缺少2天的条目。 即 17年4月6日和17年6月6日。由于当天没有交易。

我想要做的是使用

在第4和第6个日期的数据框中添加虚拟行。

提现列为 0 ,信用列为 0

“期末余额”列与前一天的最后一个期末余额条目相同。

预期产量

date      withdraw     credit    closing_balance
02/06/17    2,500.00      nan           6,396.77
03/06/17      nan      36,767.00       43,163.77
04/06/17     nan(or 0)  nan(or 0)      43,163.77
05/06/17    1,770.00      nan          41,393.77
05/06/17     6000.00      nan           35393.77
05/06/17      278.00      nan           35115.77
06/06/17    nan(or 0)   nan(or 0)       35115.77
07/06/17     1812.00      nan           33303.77

是否有执行此操作的pythonic方法。

我想首先找到丢失的日期,然后为这些日期创建一个临时数据框,然后将其与主数据框连接起来,然后进行排序。

但是我在如何获取前几天的最后一个期末余额方面存在问题,以填写缺少的几天的期末余额。

1 个答案:

答案 0 :(得分:1)

想法是使用merge添加所有缺少的日期时间,并由另一个使用最小和最大日期时间和date_range创建的DataFrame左联接。然后转发closing_balance的缺失值并为新的日期时间设置0

df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%y')

df1 = pd.DataFrame({'Date':pd.date_range(df['Date'].min(), df['Date'].max())})

df2 = df1.merge(df, how='left')
df2['closing_balance'] = df2['closing_balance'].ffill()
df2.loc[~df2['Date'].isin(df['Date']), ['withdraw','credit']] = 0
print (df2)
        Date  withdraw     credit closing_balance
0 2017-06-02  2,500.00        NaN        6,396.77
1 2017-06-03       NaN  36,767.00       43,163.77
2 2017-06-04         0          0       43,163.77
3 2017-06-05  1,770.00        NaN       41,393.77
4 2017-06-05   6000.00        NaN        35393.77
5 2017-06-05    278.00        NaN        35115.77
6 2017-06-06         0          0        35115.77
7 2017-06-07   1812.00        NaN        33303.77

使用0merge参数设置indicator值时,条件不同的相似构想:

df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%y')

df1 = pd.DataFrame({'Date':pd.date_range(df['Date'].min(), df['Date'].max())})

df2 = df1.merge(df, how='left', indicator=True)
df2['closing_balance'] = df2['closing_balance'].ffill()
df2.loc[df2.pop('_merge').eq('left_only'), ['withdraw','credit']] = 0
print (df2)
        Date  withdraw     credit closing_balance
0 2017-06-02  2,500.00        NaN        6,396.77
1 2017-06-03       NaN  36,767.00       43,163.77
2 2017-06-04         0          0       43,163.77
3 2017-06-05  1,770.00        NaN       41,393.77
4 2017-06-05   6000.00        NaN        35393.77
5 2017-06-05    278.00        NaN        35115.77
6 2017-06-06         0          0        35115.77
7 2017-06-07   1812.00        NaN        33303.77