对熊猫数据帧中每个时间序列的第一次出现和最后出现之后的NaN值进行切片

问题描述 投票:0回答:1

我研究Python 3和Pandas中的时间序列。我有一个具有多个时间序列的数据框(在此示例中为两个),每个时间序列都包含一个商店的销售数据。数据框看起来像:

                  index  Shop  Quantity
index Date                             
0     2017-01-08      0     1       NaN
1     2017-01-15      1     1       NaN
2     2017-01-22      2     1      34.0
3     2017-01-29      3     1      54.0
4     2017-02-05      4     1      42.0
5     2017-02-12      5     1       NaN
6     2017-01-08      6     2       NaN
7     2017-01-15      7     2      29.0
8     2017-01-22      8     2       NaN
9     2017-01-29      9     2      58.0
10    2017-02-05     10     2      49.0
11    2017-02-12     11     2       NaN

对于每个时间序列,我要删除NaN直到第一次出现,而NaN直到最后一次出现。它看起来应该类似于:

                  index  Shop  Quantity
index Date                             
2     2017-01-22      2     1      34.0
3     2017-01-29      3     1      54.0
4     2017-02-05      4     1      42.0
7     2017-01-15      7     2      29.0
8     2017-01-22      8     2       NaN
9     2017-01-29      9     2      58.0
10    2017-02-05     10     2      49.0

但是,下面的代码在整个第一个出现之前和之后的最后一个出现之后删除NaN,但不删除索引5和6的行:

df = df.loc[df['Quantity'].first_valid_index():df['Quantity'].last_valid_index()]
                  index  Shop  Quantity
index Date                             
2     2017-01-22      2     1      34.0
3     2017-01-29      3     1      54.0
4     2017-02-05      4     1      42.0
5     2017-02-12      5     1       NaN
6     2017-01-08      6     2       NaN
7     2017-01-15      7     2      29.0
8     2017-01-22      8     2       NaN
9     2017-01-29      9     2      58.0
10    2017-02-05     10     2      49.0

任何想法如何解决这个问题?感谢您的帮助。

python pandas dataframe time-series slice
1个回答
0
投票

用途:

l = df.index[~(df['Date']>df['Date'].shift())].to_list()
l.append(len(df))
l_mod = [0] + l + [max(l)+1]
list_of_dfs = [df.iloc[l_mod[n]:l_mod[n+1]] for n in range(len(l_mod)-1)]

df_new=pd.DataFrame(columns=df.columns)
for d in list_of_dfs:
    df_new = df_new.append(d.loc[d['Quantity'].first_valid_index():d['Quantity'].last_valid_index()])
df_new

         Date index.1 Shop  Quantity
2  2017-01-22       2    1      34.0
3  2017-01-29       3    1      54.0
4  2017-02-05       4    1      42.0
7  2017-01-15       7    2      29.0
8  2017-01-22       8    2       NaN
9  2017-01-29       9    2      58.0
10 2017-02-05      10    2      49.0
© www.soinside.com 2019 - 2024. All rights reserved.