繁体   English   中英

按日期切片多索引 pandas dataframe

[英]Slice multi-index pandas dataframe by date

假设我有以下多索引 dataframe:

arrays = [np.array(['bar', 'bar', 'bar', 'bar', 'foo', 'foo', 'foo', 'foo']),
          pd.to_datetime(['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04', '2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04'])]
df = pd.DataFrame(np.zeros((8, 4)), index=arrays)

                 0    1    2    3
bar 2020-01-01  0.0  0.0  0.0  0.0
    2020-01-02  0.0  0.0  0.0  0.0
    2020-01-03  0.0  0.0  0.0  0.0
    2020-01-04  0.0  0.0  0.0  0.0
foo 2020-01-01  0.0  0.0  0.0  0.0
    2020-01-02  0.0  0.0  0.0  0.0
    2020-01-03  0.0  0.0  0.0  0.0
    2020-01-04  0.0  0.0  0.0  0.0

我如何 select 仅此 dataframe 的第一个索引level = 'bar'date > 2020.01.02的部分,以便我可以在这部分添加 1?

更清楚地说,预期的 output 将是:

                 0    1    2    3
bar 2020-01-01  0.0  0.0  0.0  0.0
    2020-01-02  0.0  0.0  0.0  0.0
    2020-01-03  1.0  1.0  1.0  1.0
    2020-01-04  1.0  1.0  1.0  1.0
foo 2020-01-01  0.0  0.0  0.0  0.0
    2020-01-02  0.0  0.0  0.0  0.0
    2020-01-03  0.0  0.0  0.0  0.0
    2020-01-04  0.0  0.0  0.0  0.0

我根据第一个索引对其进行了切片:

df.loc['bar']

但后来我无法在日期应用条件。

这里可以比较每个级别,然后设置1 ,有:对于DataFrame.loc中的所有列:

m1 = df.index.get_level_values(0) =='bar' 
m2 = df.index.get_level_values(1) > '2020-01-02'

df.loc[m1 & m2, :] = 1
print (df)

                  0    1    2    3
bar 2020-01-01  0.0  0.0  0.0  0.0
    2020-01-02  0.0  0.0  0.0  0.0
    2020-01-03  1.0  1.0  1.0  1.0
    2020-01-04  1.0  1.0  1.0  1.0
foo 2020-01-01  0.0  0.0  0.0  0.0
    2020-01-02  0.0  0.0  0.0  0.0
    2020-01-03  0.0  0.0  0.0  0.0
    2020-01-04  0.0  0.0  0.0  0.0
#give ur index names :
df.index = df.index.set_names(["names","dates"])

#get the indices that match ur condition
index = df.query('names=="bar" and dates>"2020-01-02"').index

#assign 1 to the relevant points
#IndexSlice makes slicing multiindexes easier ... here though, it might be seen as overkill
idx = pd.IndexSlice
df.loc[idx[index],:] = 1


                 0  1   2   3
names   dates               
bar 2020-01-01  0.0 0.0 0.0 0.0
    2020-01-02  0.0 0.0 0.0 0.0
    2020-01-03  1.0 1.0 1.0 1.0
    2020-01-04  1.0 1.0 1.0 1.0
foo 2020-01-01  0.0 0.0 0.0 0.0
    2020-01-02  0.0 0.0 0.0 0.0
    2020-01-03  0.0 0.0 0.0 0.0
    2020-01-04  0.0 0.0 0.0 0.0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM